package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.UseInventoryInoutDetailDao;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.CellInventoryInoutDetailForm;
import com.wing.cabinet.model.request.UseInventoryInoutDetailForm;
import com.wing.cabinet.model.response.UseInventoryInoutDetailVO;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.constant.CabConstants;
import com.wing.order.service.DynamicService;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.model.response.ProductPackVO;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductPackService;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import com.wing.web.excel.UseInventoryUserExcelIn;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;

/**
 * 售刀柜领取/暂存柜上/暂存/维修/回收明细-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class UseInventoryInoutDetailServiceImpl extends ServiceImpl<UseInventoryInoutDetailDao, UseInventoryInoutDetail> implements UseInventoryInoutDetailService {

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private UseInventoryInoutService inventoryInoutService;

    @Autowired
    private UseInventoryProductService inventoryProductService;

    @Autowired
    private UseInventoryUserService inventoryUserService;

    @Autowired
    private UseInventoryUserKnifeService useInventoryUserKnifeService;

    @Autowired
    private UseInventoryUserKnifeSeqService useInventoryUserKnifeSeqService;

    @Autowired
    private UseInventoryUserKnifeInoutService useInventoryUserKnifeInoutService;

    @Autowired
    private UseInventoryKnifeService useInventoryKnifeService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private KnifeLifeDetailService knifeLifeDetailService;

    @Autowired
    private SkuLifeService skuLifeService;

    @Autowired
    private BrandLifeService brandLifeService;
    @Autowired
    private UserClient userClient;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    @Autowired
    private StorageInventoryKnifeService storageInventoryKnifeService;

    @Autowired
    private ProductPackService productPackService;

    @Autowired
    private CutterLifeCycleService cutterLifeCycleService;

    @Autowired
    private CellInventoryOutLabelService cellInventoryOutLabelService;

    private MathContext mathContext = new MathContext(20, RoundingMode.HALF_UP);

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;

    @Override
    public int add(UseInventoryInoutDetailForm useInventoryInoutDetailForm) {

        //校验

        UseInventoryInoutDetail useInventoryInoutDetail = new UseInventoryInoutDetail();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(UseInventoryInoutDetail.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(useInventoryInoutDetailForm, useInventoryInoutDetail, copyOptions);

        return baseMapper.insert(useInventoryInoutDetail);
    }

    @Override
    public List<UseInventoryInoutDetailVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<UseInventoryInoutDetailVO> pageList4app(Page page, Map<String, Object> params) {
        List<UseInventoryInoutDetailVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public UseInventoryInoutDetailVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    BigDecimal getTotal(List<CellInventoryInoutDetailForm> list){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            if (cellInventoryInoutDetailForm.getTotal()!=null){
                sum=sum.add(cellInventoryInoutDetailForm.getTotal());
            }
        }
        return sum;
    }

    BigDecimal getUseTotal(List<UseInventoryInoutDetailForm> list){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (UseInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            if (cellInventoryInoutDetailForm.getTotal()!=null){
                sum=sum.add(cellInventoryInoutDetailForm.getTotal());
            }
        }
        return sum;
    }

    BigDecimal getTotal(List<UseInventoryInoutDetailForm> list,UseInventoryInout.Type operationType){
        BigDecimal sum=BigDecimal.valueOf(0);
        for (UseInventoryInoutDetailForm useInventoryInoutDetailForm:list){
            if (UseInventoryInout.Type.loss.equals(operationType)||UseInventoryInout.Type.out.equals(operationType)||UseInventoryInout.Type.returned.equals(operationType)){
                List<UseInventoryKnife> skuInventoryKnifeList = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                if (skuInventoryKnifeList.size()>0){
                    useInventoryInoutDetailForm.setPrice(skuInventoryKnifeList.get(0).getPrice());
                    if (useInventoryInoutDetailForm.getPrice()!=null){
                        BigDecimal total=BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()).multiply(useInventoryInoutDetailForm.getPrice());
                        useInventoryInoutDetailForm.setTotal(total);
                        sum=sum.add(total);
                    }
                }

            }

        }
        return sum;
    }

    @Override
    @Transactional
    public UseInventoryInout inventoryIn(List<CellInventoryInoutDetailForm> list, Long cellInventoryInoutId, UseInventoryInout.BusinessType businessType, String deviceCode, String orderCode,Long storageInventoryInoutId,Long businessId) {
        log.info("进入inventoryIn接受参数cellInventoryInoutId："+cellInventoryInoutId);
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        String departmentName=JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        String channelCode=JwtUtils.getChannelCode();
        Long departmentId=JwtUtils.getDepartmentId();
        Long roleId=JwtUtils.getRoleId();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        UseInventoryInout useInventoryInout = new UseInventoryInout();
        String code = dynamicService.getDayNextCode("cab_use_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        useInventoryInout.setCode("IN-" + day + "-" + code);
        useInventoryInout.setDay(Integer.valueOf(day));
        useInventoryInout.setNo(Integer.valueOf(code));
        useInventoryInout.setCreator(JwtUtils.getLoginUserId());
        useInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        useInventoryInout.setType(UseInventoryInout.Type.in);
        useInventoryInout.setBusinessType(businessType);
        useInventoryInout.setRemark(businessType.getDesc());
        useInventoryInout.setBusinessId(cellInventoryInoutId);
        useInventoryInout.setDeviceCode(deviceCode);
        useInventoryInout.setOrderCode(orderCode);
        useInventoryInout.setCellInventoryInoutId(cellInventoryInoutId);
        useInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        useInventoryInout.setProcessId(list.get(0).getProcessId());
        useInventoryInout.setEnterpriseCode(enterpriseCode);
        useInventoryInout.setTotal(getTotal(list));
        useInventoryInout.setCreator(creator);
        useInventoryInout.setCreatorName(creatorName);
        useInventoryInout.setDepartmentName(departmentName);
        useInventoryInout.setRoleName(roleName);
        useInventoryInout.setChannelCode(channelCode);
        useInventoryInout.setRoleId(roleId);
        useInventoryInout.setDepartmentId(departmentId);
        inventoryInoutService.save(useInventoryInout);
        List<String> labelCodes = saveDetail(list, useInventoryInout.getId(), UseInventoryInout.Type.in.name(), deviceCode, orderCode, cellInventoryInoutId, null, StorageInventoryInout.BusinessDetailType.jsonCreator(businessType.name()));
        useInventoryInout.setLabelCodeList(labelCodes);
        List<UseInventoryInoutDetailForm> listIn=new ArrayList<>();
        for (CellInventoryInoutDetailForm cellInventoryInoutDetailForm:list){
            UseInventoryInoutDetailForm useInventoryInoutDetailForm=new UseInventoryInoutDetailForm();
            BeanUtils.copyProperties(cellInventoryInoutDetailForm,useInventoryInoutDetailForm);
            listIn.add(useInventoryInoutDetailForm);
        }
        sendMsg(listIn, useInventoryInout, UseInventoryInout.Type.in.name(), StorageInventoryInout.BusinessDetailType.jsonCreator(businessType.name()),creator,creatorName,enterpriseCode);
        return useInventoryInout;
    }

    @Override
    @Transactional
    public void inventoryIn4TempCabInventoryOut(List<UseInventoryInoutDetailForm> list, Long storageInventoryInoutId, UseInventoryInout.BusinessType businessType, String deviceCode, StorageInventoryInout.BusinessDetailType businessDetailType, UseInventoryInout.Type type) {
        Long creator=JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String departmentName=JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        String channelCode=JwtUtils.getChannelCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        UseInventoryInout useInventoryInout = new UseInventoryInout();
        String code = dynamicService.getDayNextCode("cab_use_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        useInventoryInout.setCode("IN-" + day + "-" + code);
        useInventoryInout.setDay(Integer.valueOf(day));
        useInventoryInout.setNo(Integer.valueOf(code));
//        useInventoryInout.setCreator(JwtUtils.getLoginUserId());
//        useInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        useInventoryInout.setType(type);
        useInventoryInout.setBusinessType(businessType);
        useInventoryInout.setRemark(businessDetailType.getDesc());
        useInventoryInout.setBusinessId(storageInventoryInoutId);
        useInventoryInout.setStorageInventoryInoutId(storageInventoryInoutId);
        useInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        useInventoryInout.setProcessId(list.get(0).getProcessId());
//        useInventoryInout.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        useInventoryInout.setDeviceCode(deviceCode);
        useInventoryInout.setTotal(getUseTotal(list));
        useInventoryInout.setCreator(creator);
        useInventoryInout.setCreatorName(creatorName);
        useInventoryInout.setEnterpriseCode(enterpriseCode);
        useInventoryInout.setDepartmentName(departmentName);
        useInventoryInout.setRoleName(roleName);
        useInventoryInout.setRoleId(roleId);
        useInventoryInout.setChannelCode(channelCode);
        if (StringUtils.isBlank(deviceCode)) {
            useInventoryInout.setDeviceCode(list.get(0).getDeviceCode());
            deviceCode = list.get(0).getDeviceCode();
        }
        inventoryInoutService.save(useInventoryInout);
        saveDetail4UseInoutDetailForm(list, useInventoryInout.getId(), UseInventoryInout.Type.in.name(), businessType.name(), deviceCode, storageInventoryInoutId, businessDetailType);
        sendMsg(list, useInventoryInout, type.name(), businessDetailType,creator,creatorName,enterpriseCode);
    }

    @Override
    @Transactional
    public void inventoryIn4RepairOrderSign(List<StorageInventoryInoutDetail> list, Long businessId, UseInventoryInout.BusinessType businessType) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        UseInventoryInout useInventoryInout = new UseInventoryInout();
        String code = dynamicService.getDayNextCode("cab_use_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        useInventoryInout.setCode("IN-" + day + "-" + code);
        useInventoryInout.setDay(Integer.valueOf(day));
        useInventoryInout.setNo(Integer.valueOf(code));
        useInventoryInout.setCreator(JwtUtils.getLoginUserId());
        useInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        useInventoryInout.setType(UseInventoryInout.Type.in);
        useInventoryInout.setBusinessType(businessType);
        useInventoryInout.setBusinessId(businessId);
        useInventoryInout.setStorageInventoryInoutId(businessId);
        inventoryInoutService.save(useInventoryInout);
        List<CellInventoryInoutDetailForm> listIn = new ArrayList<>();
        for (StorageInventoryInoutDetail detailForm : list) {
            CellInventoryInoutDetailForm cellInventoryInoutDetailForm = new CellInventoryInoutDetailForm();
            BeanUtils.copyProperties(detailForm, cellInventoryInoutDetailForm);
            listIn.add(cellInventoryInoutDetailForm);
        }
        saveDetail(listIn, useInventoryInout.getId(), UseInventoryInout.Type.in.name(), null, useInventoryInout.getCode(), null, businessId, StorageInventoryInout.BusinessDetailType.repairOrderSign);
    }

    @Override
    @Transactional
    public void inventoryOut(List<UseInventoryInoutDetailForm> list, Long storageInventoryInoutId, String deviceCode, StorageInventoryInout.BusinessType businessType, UseInventoryInout.Type type, StorageInventoryInout.BusinessDetailType businessDetailType,String remark) {
        if (StringUtils.isBlank(deviceCode)){
            deviceCode=list.get(0).getDeviceCode();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        UseInventoryInout useInventoryInout = new UseInventoryInout();
        String code = dynamicService.getDayNextCode("cab_use_inventory_inout");
        String day = simpleDateFormat.format(new Date());
        String channelCode=JwtUtils.getChannelCode();
        Long roleId=JwtUtils.getRoleId();
        String roleName=JwtUtils.getRoleName();
        Long departmentId=JwtUtils.getDepartmentId();
        String departmentName=JwtUtils.getDepartmentName();
        useInventoryInout.setCode("OU-" + day + "-" + code);
        useInventoryInout.setDay(Integer.valueOf(day));
        useInventoryInout.setNo(Integer.valueOf(code));
        useInventoryInout.setCreator(JwtUtils.getLoginUserId());
        useInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
        useInventoryInout.setType(type);
        useInventoryInout.setBusinessId(storageInventoryInoutId);
        useInventoryInout.setDeviceCode(deviceCode);
        useInventoryInout.setStorageInventoryInoutId(storageInventoryInoutId);
        useInventoryInout.setBusinessType(UseInventoryInout.BusinessType.jsonCreator(businessDetailType.name()));
        useInventoryInout.setRemark(useInventoryInout.getBusinessType() != null ? useInventoryInout.getBusinessType().getDesc() : "");
        useInventoryInout.setWorkOrderId(list.get(0).getWorkOrderId());
        useInventoryInout.setProcessId(list.get(0).getProcessId());
        useInventoryInout.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        useInventoryInout.setDeviceCode(deviceCode);
        if (StringUtils.isBlank(deviceCode)) {
            useInventoryInout.setDeviceCode(list.get(0).getDeviceCode());
        }
        useInventoryInout.setTotal(getTotal(list,useInventoryInout.getType()));
        useInventoryInout.setChannelCode(channelCode);
        useInventoryInout.setRoleId(roleId);
        useInventoryInout.setRoleName(roleName);
        useInventoryInout.setDepartmentId(departmentId);
        useInventoryInout.setDepartmentName(departmentName);
        useInventoryInout.setCostCenter(JwtUtils.getCostCenter());
        useInventoryInout.setRemark(remark);
        inventoryInoutService.save(useInventoryInout);
        List<CellInventoryInoutDetailForm> listOut = new ArrayList<>();
        for (UseInventoryInoutDetailForm detailForm : list) {
            CellInventoryInoutDetailForm cellInventoryInoutDetailForm = new CellInventoryInoutDetailForm();
            BeanUtils.copyProperties(detailForm, cellInventoryInoutDetailForm);
            listOut.add(cellInventoryInoutDetailForm);
        }
        if (UseInventoryInout.Type.returned.equals(type)) {
            // 获取批量还刀的条码
            List<String> labelCodeList = new ArrayList<>();
            for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                // 通过use_inventory_user_id查询表cab_use_inventory_user_knife(刀具编号)
                List<UseInventoryKnife> inventoryKnives = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("use_inventory_user_id", useInventoryInoutDetailForm.getId()));
                for (UseInventoryKnife inventoryKnife : inventoryKnives) {
                    labelCodeList.add(inventoryKnife.getLabelCode());
                }
            }
            saveDetail4Return(listOut, useInventoryInout.getId(), type.name(), deviceCode, useInventoryInout.getCode(), null, storageInventoryInoutId, businessDetailType);
            if(businessType.equals(StorageInventoryInout.BusinessType.outByReturned)){
                // 添加刀具生命周期  --  批量还刀
                cutterLifeCycleService.addLifeCycle(labelCodeList, CutterLifeCycle.Status.batchReturn, businessDetailType, null, useInventoryInout.getCode(), deviceCode);
            }
        }else if(UseInventoryInout.Type.loss.equals(type)){
            saveDetail4Loss(listOut, useInventoryInout.getId(), type.name(), deviceCode, useInventoryInout.getCode(), null, storageInventoryInoutId, businessDetailType);
            // 添加刀具生命周期
            List<String> labelCodeList = new ArrayList<>();
            for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                labelCodeList.add(useInventoryInoutDetailForm.getLabelCode());
            }
            // 添加刀具生命周期  --  报失
            cutterLifeCycleService.addLifeCycle(labelCodeList, CutterLifeCycle.Status.loss, businessDetailType, null, useInventoryInout.getCode(), deviceCode);
        }
        else {
            saveDetail(listOut, useInventoryInout.getId(), type.name(), deviceCode, useInventoryInout.getCode(), null, storageInventoryInoutId, businessDetailType);
        }
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        sendMsg(list, useInventoryInout, type.name(), businessDetailType,creator,creatorName,enterpriseCode);
    }

    void sendMsg(List<UseInventoryInoutDetailForm> list, UseInventoryInout useInventoryInout, String inOutTypeName, StorageInventoryInout.BusinessDetailType businessDetailType, Long creator,String creatorName,String enterpriseCode) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            syncData(list, useInventoryInout, inOutTypeName, businessDetailType,creator,creatorName,enterpriseCode);
                        } catch (Exception e) {
                            log.error("syn fail", e);
                        }

                    }
                });
            }
        });
    }


    /*
    数据同步
     */
    public void syncData(List<UseInventoryInoutDetailForm> list, UseInventoryInout useInventoryInout, String inOutTypeName, StorageInventoryInout.BusinessDetailType businessDetailType, Long creator,String creatorName,String enterpriseCode) {

//        DynamicDataSource.name.set(enterpriseCode.toLowerCase());

        try {
            //  同步cab_use_inventory_inout:在用存取领出记录
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            useInventoryInout.setSynsTime(LocalDateTime.now());
            useInventoryInout.setCreator(creator).setCreatorName(creatorName).setEnterpriseCode(enterpriseCode).setUniqCode(enterpriseCode+"-"+useInventoryInout.getId());
            jsonObject.put("data", useInventoryInout);

            PulsarUtils.send(topicUrl + PulsarCommons.CAB_USE_INVENTORY_INOUT, jsonObject.toJSONString());
        } catch (Exception e) {
            log.error("sync cab_use_inventory_inout 同步失败", e);
            UseInventoryInout useInventoryInoutUpdate=new UseInventoryInout();
            useInventoryInoutUpdate.setId(useInventoryInout.getId());
            useInventoryInoutUpdate.setIsSyns(0);
            inventoryInoutService.updateById(useInventoryInoutUpdate);

        }
        // 同步cab_use_inventory_inout_detail:在用存取领出记录明细
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            LambdaQueryWrapper<UseInventoryInoutDetail> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(UseInventoryInoutDetail::getInoutId,useInventoryInout.getId());
            List<UseInventoryInoutDetail> detailList = this.list(lambdaQueryWrapper);
            detailList.forEach(s ->{s.setSkuCode(enterpriseCode+"-"+s.getSkuCode());s.setInoutUniqCode(enterpriseCode+"-"+s.getInoutId());});

            jsonObject.put("data", detailList);
            PulsarUtils.send(topicUrl + PulsarCommons.CAB_USE_INVENTORY_INOUT_DETAIL, jsonObject.toJSONString());
        }catch (Exception e){
            log.error("sync cab_use_inventory_inout_detail 失败", e);
            Stream.iterate(0,i -> i+1).limit(list.size()).forEach( i ->{
                UseInventoryInoutDetail inoutDetail =  new UseInventoryInoutDetail();
                inoutDetail.setId(list.get(i).getId());
                inoutDetail.setIsSyns(0);
                baseMapper.updateById(inoutDetail);
            });
        }

        //  cab_use_inventory_user 用户产品在用库存
        //  cab_use_inventory_product 产品在用库存
        Stream.iterate(0,i->i+1).limit(list.size()).forEach(i -> {
            List<UseInventoryProduct> skuInventoryList = new ArrayList<>();
            skuInventoryList = inventoryProductService.list(new QueryWrapper<UseInventoryProduct>().eq("sku_code", list.get(i).getSkuCode()));
            try {
//
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                if (skuInventoryList.size()>0){
                    for (int j = 0; j < skuInventoryList.size(); j++) {
                        skuInventoryList.get(j).setSkuCode(skuInventoryList.get(j).getEnterpriseCode()+"-"+skuInventoryList.get(j).getSkuCode());
                    }
                }else {

                    UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                    useInventoryProduct.setQuantity(0);
                    useInventoryProduct.setSkuCode(enterpriseCode+"-"+list.get(i).getSkuCode()).setEnterpriseCode(enterpriseCode);
                    skuInventoryList.add(useInventoryProduct);
                }
                jsonObject.put("data", skuInventoryList);

                PulsarUtils.send(topicUrl + PulsarCommons.CAB_USE_INVENTORY_PRODUCT, jsonObject.toJSONString());
            }catch (Exception e){
                log.error("sync cab_use_inventory_product 失败", e);
                for ( UseInventoryProduct inventoryProduct : skuInventoryList) {
                    if (inventoryProduct.getId()!=null){
                        UseInventoryProduct useInventoryProductUpdate=new UseInventoryProduct();
                        useInventoryProductUpdate.setId(inventoryProduct.getId());
                        useInventoryProductUpdate.setIsSyns(0);
                        inventoryProductService.updateById(useInventoryProductUpdate);
                    }

                }
            }
        });

    }

    @Override
    @Transactional(readOnly = false)
    public void inventoryOut(List<UseInventoryInoutDetailForm> list, StorageInventoryInout.BusinessType businessType, UseInventoryInout.Type type,StorageInventoryInout.BusinessDetailType businessDetailType,String remark) {
        inventoryOut(list, null, null, businessType, type, businessDetailType,remark);
    }

    @Transactional
    List<String> saveDetail4Return(List<CellInventoryInoutDetailForm> list, Long inventoryInoutId, String inOutTypeName, String deviceCode, String orderCode, Long cellInventoryInoutId, Long storageInventoryInoutId, StorageInventoryInout.BusinessDetailType businessDetailType) {
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        boolean lifeFlag = false;
        if (systemRuleInfo != null) {
            lifeFlag = systemRuleInfo.getLifeFlag();
        }
        List<String> labelCodes = new ArrayList<>();
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long departmentId = JwtUtils.getDepartmentId();
        String departmentName = JwtUtils.getDepartmentName();
        String channelCode=JwtUtils.getChannelCode();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        Integer year = LocalDateTime.now().getYear();
        Integer month = LocalDateTime.now().getMonthValue();
        if (CollectionUtils.isNotEmpty(list)) {
            for (CellInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                if (null == useInventoryInoutDetailForm.getPackId() || useInventoryInoutDetailForm.getPackId().equals(0)) {
                    //useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                    //useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                    //useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                    //useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                    throw new BusinessException("请选择合适的包装方案");
                }
                //else{

                ProductPackVO productPackVO = productPackService.get4appById(useInventoryInoutDetailForm.getPackId());
                if (null != productPackVO){
                    useInventoryInoutDetailForm.setPackId(productPackVO.getId());
                    useInventoryInoutDetailForm.setPackName(productPackVO.getName());
                    useInventoryInoutDetailForm.setUnitName(productPackVO.getPackUnitName());
                    useInventoryInoutDetailForm.setQuantityPackUnit(productPackVO.getBaseRate());
                }else{
                    useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                    useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                    useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                    useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
               // }
                UseInventoryInoutDetail useInventoryInoutDetail = new UseInventoryInoutDetail();
                BeanUtils.copyProperties(useInventoryInoutDetailForm, useInventoryInoutDetail);
                useInventoryInoutDetail.setId(null);
                useInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                useInventoryInoutDetail.setCreator(creator);
                useInventoryInoutDetail.setCreatorName(creatorName);
                useInventoryInoutDetail.setType(UseInventoryInoutDetail.Type.jsonCreator(inOutTypeName));
                useInventoryInoutDetail.setBusinessType(UseInventoryInoutDetail.BusinessType.jsonCreator(businessDetailType.name()));
                useInventoryInoutDetail.setInoutId(inventoryInoutId);
                useInventoryInoutDetail.setChannelCode(channelCode);
                List<UseInventoryProduct> skuInventoryList = inventoryProductService.list(new QueryWrapper<UseInventoryProduct>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("enterprise_code", enterpriseCode));

                if (UseInventoryInout.Type.out.name().equals(inOutTypeName) ||
                        UseInventoryInout.Type.returned.name().equals(inOutTypeName)||
                        UseInventoryInout.Type.loss.name().equals(inOutTypeName)) {

//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",useInventoryInoutDetailForm.getCreator()));
                    List<UseInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id", useInventoryInoutDetailForm.getId()));
//                    List<UseInventoryKnife> skuInventoryKnifeList=useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id",useInventoryInoutDetailForm.getId()));
                    if (skuInventoryUserList.size() == 0) {
                        throw new BusinessException("未找到SKU[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品");
                    } else {
                        List<UseInventoryKnife> skuInventoryKnifes = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("use_inventory_user_id", useInventoryInoutDetailForm.getId()));
                        for (UseInventoryKnife useInventoryKnife : skuInventoryKnifes) {

//                        List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id",skuInventoryKnifeList.get(0).getUseInventoryUserId()));

                            UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                            ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(useInventoryInoutDetailForm.getSkuCode());

                            UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();

                            if (lifeFlag && productDetailVO != null && productDetailVO.getLifeSpan() != null && productDetailVO.getLifeSpan() != 0 &&
                                    list.get(0).getUseTime() != null && list.get(0).getUseTime() != 0) {

                                KnifeLifeDetail knifeLifeDetail = new KnifeLifeDetail();
                                knifeLifeDetail.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                                knifeLifeDetail.setOutTime(useInventoryKnife.getOutTime());
                                knifeLifeDetail.setInTime(LocalDateTime.now());
                                knifeLifeDetail.setInCreator(useInventoryKnife.getCreator());
                                knifeLifeDetail.setInCreatorName(useInventoryKnife.getCreatorName());
                                knifeLifeDetail.setOutCreator(creator);
                                knifeLifeDetail.setOutCreatorName(creatorName);
                                if (useInventoryKnife.getBusinessType() != null) {
                                    knifeLifeDetail.setOutBusinessType(KnifeLifeDetail.OutBusinessType.jsonCreator(useInventoryKnife.getBusinessType().name()));
                                }
                                knifeLifeDetail.setInBusinessType(KnifeLifeDetail.InBusinessType.jsonCreator(businessDetailType.name()));
                                knifeLifeDetail.setPreTime(useInventoryKnife.getRemainingTime());
                                knifeLifeDetail.setUseTime(list.get(0).getUseTime());
                                knifeLifeDetail.setSkuCode(useInventoryKnife.getSkuCode());
                                if (productDetailVO != null) {
                                    knifeLifeDetail.setProductCode(productDetailVO.getProductCode());
                                    knifeLifeDetail.setBrandId(productDetailVO.getBrandId());
                                }
                                Integer remainingTime = 0;
                                Integer sumUsedTime = 0;
                                Integer settingTime = 0;
                                if (useInventoryKnife.getSettingTime() == null) {
                                    useInventoryKnife.setSettingTime(productDetailVO.getLifeSpan());
                                }
                                if (useInventoryKnife.getRemainingTime() == null) {
                                    remainingTime = productDetailVO.getLifeSpan() - list.get(0).getUseTime();
                                    sumUsedTime = list.get(0).getUseTime();
                                    settingTime = productDetailVO.getLifeSpan();
                                    if (productDetailVO.getLifeUnit() != null) {
                                        knifeLifeDetail.setLifeUnit(KnifeLifeDetail.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                    }
//                                StorageInventoryKnife useInventoryKnife4Update=new StorageInventoryKnife();
//                                useInventoryKnife4Update.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
//                                useInventoryKnife4Update.setRemainingTime(remainingTime);
//                                storageInventoryKnifeService.updateRemainingTime(remainingTime,useInventoryInoutDetailForm.getLabelCode());
                                } else {
                                    remainingTime = useInventoryKnife.getRemainingTime() - list.get(0).getUseTime();
                                    sumUsedTime = useInventoryKnife.getSettingTime() - remainingTime;
                                    settingTime = useInventoryKnife.getSettingTime();
                                    if (useInventoryKnife.getLifeUnit() != null) {
                                        knifeLifeDetail.setLifeUnit(KnifeLifeDetail.LifeUnit.jsonCreator(useInventoryKnife.getLifeUnit().name()));
                                    }
                                }
                                useInventoryUserKnifeInout.setUseTime(list.get(0).getUseTime());
                                useInventoryUserKnifeInout.setRemainingTime(remainingTime);
                                useInventoryUserKnifeInout.setPreTime(useInventoryKnife.getRemainingTime());
                                if (useInventoryKnife.getLifeUnit() != null) {
                                    useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(useInventoryKnife.getLifeUnit().name()));
                                }


                                storageInventoryKnifeService.updateRemainingTime(remainingTime, useInventoryInoutDetailForm.getLabelCode());

                                knifeLifeDetail.setRemainingTime(remainingTime);
                                knifeLifeDetail.setRemark(knifeLifeDetail.getInBusinessTypeDesc());
                                knifeLifeDetail.setEnterpriseCode(enterpriseCode);


                                knifeLifeDetailService.save(knifeLifeDetail);
                                useInventoryUserKnife.setUseTime(list.get(0).getUseTime());
                                useInventoryUserKnife.setRemainingTime(remainingTime);


//                            useInventoryUserKnife.setSumTime();


                                if (StorageInventoryInout.BusinessDetailType.tempIn.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.tempInByOldNew.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.repairIn.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.repairInByOldNew.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.recycleIn.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.recycleInByOldNew.equals(businessDetailType)
                                ) {
                                    List<SkuLife> skuLives = skuLifeService.list(new QueryWrapper<SkuLife>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("year", year).eq("month", month).eq("enterprise_code", enterpriseCode));

                                    if (skuLives.size() > 0) {
                                        SkuLife skuLife = skuLives.get(0);
                                        if (UseInventoryKnife.BusinessType.cellCabOut.equals(useInventoryKnife.getBusinessType()) ||
                                                UseInventoryKnife.BusinessType.cellCabOutByOldNew.equals(useInventoryKnife.getBusinessType())) {
                                            skuLife.setQuantity(skuLives.get(0).getQuantity() + 1);
                                        }
                                        skuLife.setSumTime(skuLives.get(0).getSumTime() + list.get(0).getUseTime());
                                        skuLife.setId(skuLives.get(0).getId());
                                        skuLifeService.updateById(skuLife);
                                    } else {
                                        SkuLife skuLife = new SkuLife();
                                        skuLife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                                        skuLife.setSumTime(list.get(0).getUseTime());
                                        skuLife.setQuantity(1);
                                        skuLife.setProductCode(productDetailVO.getProductCode());
                                        skuLife.setBrandId(productDetailVO.getBrandId());
                                        skuLife.setSettingTime(productDetailVO.getLifeSpan());
                                        if (productDetailVO.getLifeUnit() != null) {
                                            skuLife.setLifeUnit(SkuLife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                        }

                                        skuLife.setEnterpriseCode(enterpriseCode);
                                        skuLife.setYear(year);
                                        skuLife.setMonth(month);
                                        skuLifeService.save(skuLife);
                                    }
                                    if (productDetailVO.getBrandId() != null) {
                                        if (StorageInventoryInout.BusinessDetailType.repairIn.equals(businessDetailType) ||
                                                StorageInventoryInout.BusinessDetailType.repairInByOldNew.equals(businessDetailType) ||
                                                StorageInventoryInout.BusinessDetailType.recycleIn.equals(businessDetailType) ||
                                                StorageInventoryInout.BusinessDetailType.recycleInByOldNew.equals(businessDetailType)) {

                                            if (settingTime != null && sumUsedTime != null && settingTime != 0) {
                                                BigDecimal lifeRate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);
                                                String lifeRateStr = new DecimalFormat("0.0000").format(lifeRate);
                                                useInventoryUserKnife.setRate(BigDecimal.valueOf(Double.valueOf(lifeRateStr)));
                                            }

                                            List<BrandLife> brandLives = brandLifeService.list(new QueryWrapper<BrandLife>().eq("brand_id", productDetailVO.getBrandId()).eq("year", year).eq("month", month).eq("enterprise_code", enterpriseCode));
//                                        Integer sumUsedTime=productDetailVO.getLifeSpan()-remainingTime;
                                            if (sumUsedTime != null && sumUsedTime != null && settingTime.doubleValue() != 0) {
                                                if (brandLives.size() > 0) {

                                                    BrandLife brandLife = brandLives.get(0);
                                                    brandLife.setId(brandLives.get(0).getId());
                                                    BigDecimal lifeRate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);

                                                    if (brandLives.get(0).getSumRate() == null) {
                                                        brandLives.get(0).setSumRate(BigDecimal.valueOf(0));
                                                    }
                                                    if (brandLives.get(0).getQuantity() == null) {
                                                        brandLives.get(0).setQuantity(0);
                                                    }
                                                    if (brandLives.get(0).getUseTime() == null) {
                                                        brandLives.get(0).setUseTime(0);
                                                    }
                                                    if (brandLives.get(0).getSumTime() == null) {
                                                        brandLives.get(0).setSumTime(0);
                                                    }
                                                    BigDecimal sumRate = lifeRate.add(brandLives.get(0).getSumRate());
                                                    BigDecimal avgRate = sumRate.divide(BigDecimal.valueOf(brandLives.get(0).getQuantity() + 1), mathContext);
                                                    DecimalFormat df = new DecimalFormat("0.0000");
                                                    String avgRateVal = df.format(avgRate.doubleValue());
                                                    brandLife.setRate(BigDecimal.valueOf(Double.valueOf(avgRateVal)));
                                                    brandLife.setSumRate(sumRate);
                                                    brandLife.setUseTime(brandLives.get(0).getUseTime() + sumUsedTime);
                                                    brandLife.setSumTime(brandLives.get(0).getSumTime() + settingTime);
                                                    brandLife.setQuantity(brandLives.get(0).getQuantity() + 1);
                                                    brandLifeService.updateById(brandLife);


                                                } else {
                                                    BrandLife brandLife = new BrandLife();
                                                    brandLife.setBrandId(productDetailVO.getBrandId());
                                                    brandLife.setUseTime(sumUsedTime);
                                                    brandLife.setSumTime(settingTime);
                                                    BigDecimal rate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);
                                                    DecimalFormat df = new DecimalFormat("0.0000");
                                                    String rateVal = df.format(rate.doubleValue());
                                                    brandLife.setRate(BigDecimal.valueOf(Double.valueOf(rateVal)));
                                                    brandLife.setSumRate(brandLife.getRate());
                                                    brandLife.setEnterpriseCode(enterpriseCode);
                                                    brandLife.setYear(year);
                                                    brandLife.setMonth(month);
                                                    brandLife.setQuantity(1);
                                                    if (productDetailVO.getLifeUnit() != null) {
                                                        brandLife.setLifeUnit(BrandLife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                                    }

                                                    brandLifeService.save(brandLife);
                                                }
                                            }

                                        }

                                    }
                                }


                            }


                            useInventoryKnifeService.remove(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryKnife.getId()));
                            if (UseInventoryInout.Type.out.name().equals(inOutTypeName)) {
                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
                                useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
                            }else if(UseInventoryInout.Type.returned.name().equals(inOutTypeName)){
                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.returned);
                                useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.returned);
                            }else if(UseInventoryInout.Type.loss.name().equals(inOutTypeName)){
                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.loss);
                                useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.loss);
                            }

                            useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                            useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                            useInventoryUserKnife.setInTime(LocalDateTime.now());
                            useInventoryUserKnife.setCode(useInventoryKnife.getLabelCode());
                            useInventoryUserKnife.setCategoryId(useInventoryInoutDetailForm.getCategoryId());
//                        useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
                            useInventoryUserKnifeService.updateKnife(useInventoryUserKnife);


                            useInventoryUserKnifeInout.setCode(useInventoryKnife.getLabelCode());
                            useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            useInventoryUserKnifeInout.setUseInventoryUserId(useInventoryKnife.getUseInventoryUserId());
                            useInventoryUserKnifeInout.setUseInventoryInoutId(inventoryInoutId);
                            useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
//                        useInventoryUserKnifeInout.setCellInventoryInoutId(cellInventoryInoutId);
                            useInventoryUserKnifeInout.setDeviceCode(deviceCode);

                            useInventoryUserKnifeInout.setCreator(creator);
                            useInventoryUserKnifeInout.setCreatorName(creatorName);
                            useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                            useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessType() != null ? useInventoryUserKnifeInout.getBusinessType().getDesc() : "");
                            useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                            useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                            useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                            useInventoryUserKnifeInout.setCategoryId(useInventoryInoutDetailForm.getCategoryId());
                            useInventoryUserKnifeInout.setChannelCode(channelCode);
                            useInventoryUserKnifeInout.setDepartmentName(departmentName);
                            useInventoryUserKnifeInout.setDepartmentId(departmentId);
                            useInventoryUserKnifeInout.setRoleName(roleName);
                            useInventoryUserKnifeInout.setRoleId(roleId);
                            useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);

                        }
                    }
                    Integer quantity = useInventoryInoutDetailForm.getQuantity();
                    if (quantity > 0) {
                        quantity = -1 * quantity;
                    }
                    if (skuInventoryUserList.size() > 0) {
                        Integer currentQuantity = skuInventoryUserList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                                throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                        }

                        UseInventoryUser useInventoryUser = new UseInventoryUser();
                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUser.setQuantity(newQuantity);
                        if (newQuantity <= 0) {
                            inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                        } else {
                            inventoryUserService.updateById(useInventoryUser);
                        }

                        if (skuInventoryList.size() > 0) {
                            useInventoryInoutDetail.setQuantityCurrent(skuInventoryList.get(0).getQuantity());
                            useInventoryInoutDetail.setQuantityAfter(skuInventoryList.get(0).getQuantity() + quantity);
                        } else {
                            useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                            useInventoryInoutDetail.setQuantityAfter(newQuantity);
                        }
                    }

//                        if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getLabelCode())){
//                            UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                            useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                            useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
//                        }else{
//                            List<UseInventoryUserKnife> useInventoryUserKnives=useInventoryUserKnifeService.list(new QueryWrapper<UseInventoryUserKnife>().eq("use_inventory_user_id",useInventoryInoutDetailForm.getId()).eq("status",UseInventoryUserKnife.Status.used.getValue()));
//                            int size=useInventoryUserKnives.size();
//                            if (size>useInventoryInoutDetailForm.getQuantity()){
//                                size=useInventoryInoutDetailForm.getQuantity();
//                            }
//                            for (int i=0;i<size;i++){
//                                UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                                useInventoryUserKnife.setId(useInventoryUserKnives.get(i).getId());
//                                useInventoryUserKnifeService.updateById(useInventoryUserKnife);
//                            }
//                        }


                    useInventoryInoutDetail.setQuantity(quantity);
                    useInventoryInoutDetail.setCreator(useInventoryInoutDetailForm.getCreator());
                    useInventoryInoutDetail.setCreatorName(useInventoryInoutDetailForm.getCreatorName());
                    useInventoryInoutDetail.setModifier(creator);
                    useInventoryInoutDetail.setModifierName(creatorName);
                    useInventoryInoutDetail.setQuantityPack(useInventoryInoutDetail.getQuantity());
                    baseMapper.insert(useInventoryInoutDetail);


//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException("未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
//                    }else{
                    if (skuInventoryList.size() > 0) {


                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                            throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                            newQuantity = 0;
                        }

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        if (newQuantity <= 0) {
                            inventoryProductService.removeById(skuInventoryList.get(0).getId());
                        } else {
                            inventoryProductService.updateById(useInventoryProduct);
                        }


//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(useInventoryInoutDetail);
                    }

//                    }
                } else if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",creator));

//                    Integer quantity=useInventoryInoutDetailForm.getQuantity();
                    List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                    if (useInventoryInoutDetailForm.getQuantity() < 0) {
                        throw new BusinessException("领取数量参数异常");
                    }
                    if (skuInventoryList.size() == 0) {
                        Integer currentQuantity = 0;
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        useInventoryProduct.setDeviceCode(deviceCode);
                        useInventoryProduct.setEnterpriseCode(enterpriseCode);
                        useInventoryProduct.setCreator(creator);
                        useInventoryProduct.setCreatorName(creatorName);
                        useInventoryProduct.setEnterpriseCode(enterpriseCode);
                        useInventoryProduct.setChannelCode(channelCode);
                        /**
                         * 默认包装单位 一粒/片
                         */
                        useInventoryProduct.setPackId(useInventoryInoutDetailForm.getPackId());
                        useInventoryProduct.setPackName(useInventoryInoutDetailForm.getPackName());
                        useInventoryProduct.setUnitName(useInventoryInoutDetailForm.getUnitName());
                        useInventoryProduct.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                        useInventoryProduct.setQuantityPack(newQuantity);
                        inventoryProductService.save(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        baseMapper.insert(useInventoryInoutDetail);
                    } else {

                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        inventoryProductService.updateById(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        baseMapper.insert(useInventoryInoutDetail);
                    }
//                    quantity=useInventoryInoutDetailForm.getQuantity();
//                    if (skuInventoryUserList.size()==0){
//                        Integer currentQuantity=0;
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                    UseInventoryUser useInventoryUser = new UseInventoryUser();
                    useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    useInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    useInventoryUser.setCreator(creator);
                    useInventoryUser.setCreatorName(creatorName);
                    useInventoryUser.setDeviceCode(deviceCode);
                    useInventoryUser.setOrderCode(orderCode);
                    useInventoryUser.setCellInventoryInoutId(cellInventoryInoutId);
                    useInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    useInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    useInventoryUser.setUseInventoryInoutId(inventoryInoutId);
                    useInventoryUser.setUseInventoryInoutDetailId(useInventoryInoutDetail.getId());
                    useInventoryUser.setWorkOrderId(list.get(0).getWorkOrderId());
                    useInventoryUser.setDepartmentId(departmentId);
                    useInventoryUser.setDepartmentName(departmentName);
                    useInventoryUser.setEnterpriseCode(enterpriseCode);
                    useInventoryUser.setBusinessType(UseInventoryUser.BusinessType.jsonCreator(businessDetailType.name()));
                    useInventoryUser.setRemark(useInventoryUser.getBusinessTypeDesc());
                    useInventoryUser.setChannelCode(channelCode);
                    useInventoryUser.setDepartmentName(departmentName);
                    useInventoryUser.setDepartmentId(departmentId);
                    useInventoryUser.setRoleName(roleName);
                    useInventoryUser.setRoleId(roleId);
                    /**
                     * 默认包装单位 一粒/片
                     */
                    useInventoryUser.setPackId(useInventoryInoutDetailForm.getPackId());
                    useInventoryUser.setPackName(useInventoryInoutDetailForm.getPackName());
                    useInventoryUser.setUnitName(useInventoryInoutDetailForm.getUnitName());
                    useInventoryUser.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                    useInventoryUser.setQuantityPack(useInventoryInoutDetailForm.getQuantity());
                    inventoryUserService.save(useInventoryUser);

                    for (int i = 0; i < useInventoryInoutDetailForm.getQuantity(); i++) {
                        UseInventoryUserKnifeSeq useInventoryUserKnifeSeq = new UseInventoryUserKnifeSeq();
                        useInventoryUserKnifeSeqService.insert(useInventoryUserKnifeSeq);
                        Long labelId = useInventoryUserKnifeSeqService.getId();
                        String labelCode = StringUtils.leftPad(labelId.toString(), 10, "0");
                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                        useInventoryUserKnife.setCode(labelCode);
                        useInventoryUserKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUserKnife.setUseInventoryUserId(useInventoryUser.getId());
                        useInventoryUserKnife.setUseInventoryInoutId(inventoryInoutId);
                        useInventoryUserKnife.setCellInventoryInoutId(cellInventoryInoutId);
                        useInventoryUserKnife.setDeviceCode(deviceCode);
                        useInventoryUserKnife.setCreator(creator);
                        useInventoryUserKnife.setCreatorName(creatorName);
                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                        useInventoryUserKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnife.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryUserKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryUserKnife.setOutTime(LocalDateTime.now());
                        useInventoryUserKnife.setChannelCode(channelCode);
                        useInventoryUserKnife.setDepartmentName(departmentName);
                        useInventoryUserKnife.setDepartmentId(departmentId);
                        useInventoryUserKnife.setRoleName(roleName);
                        useInventoryUserKnife.setRoleId(roleId);

                        UseInventoryKnife useInventoryKnife = new UseInventoryKnife();
                        UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();

                        if (productDetails.size() > 0) {
                            if (productDetails.get(0).getLifeSpan() != null) {
                                useInventoryUserKnife.setInitTime(productDetails.get(0).getLifeSpan());
                                useInventoryUserKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                useInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                useInventoryKnife.setSettingTime(productDetails.get(0).getLifeSpan());

                                useInventoryUserKnifeInout.setInitTime(productDetails.get(0).getLifeSpan());
                                useInventoryUserKnifeInout.setRemainingTime(productDetails.get(0).getLifeSpan());
                            }

                            if (productDetails.get(0).getLifeUnit() != null) {
                                useInventoryKnife.setLifeUnit(UseInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                useInventoryUserKnife.setLifeUnit(UseInventoryUserKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                            }

                        }
                        useInventoryUserKnifeService.save(useInventoryUserKnife);


                        useInventoryKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryKnife.setQuantity(1);
                        useInventoryKnife.setCreator(creator);
                        useInventoryKnife.setCreatorName(creatorName);
                        useInventoryKnife.setDeviceCode(deviceCode);
                        useInventoryKnife.setOrderCode(orderCode);
                        useInventoryKnife.setCellInventoryInoutId(cellInventoryInoutId);
                        useInventoryKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryKnife.setUseInventoryInoutId(inventoryInoutId);
                        useInventoryKnife.setUseInventoryInoutDetailId(useInventoryInoutDetail.getId());
                        useInventoryKnife.setLabelCode(labelCode);
                        useInventoryKnife.setUseInventoryUserId(useInventoryUser.getId());
                        useInventoryKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryKnife.setEnterpriseCode(enterpriseCode);
                        useInventoryKnife.setOutTime(LocalDateTime.now());
                        useInventoryKnife.setBusinessType(UseInventoryKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryKnife.setRemark(useInventoryKnife.getBusinessTypeDesc());
                        useInventoryKnife.setChannelCode(channelCode);
                        useInventoryKnife.setDepartmentName(departmentName);
                        useInventoryKnife.setDepartmentId(departmentId);
                        useInventoryKnife.setRoleName(roleName);
                        useInventoryKnife.setRoleId(roleId);
                        useInventoryKnife.setPackId(useInventoryInoutDetailForm.getPackId());
                        useInventoryKnife.setPackName(useInventoryInoutDetailForm.getPackName());
                        /**
                         if (productDetails.size()>0){
                         if (productDetails.get(0).getLifeSpan()!=null){
                         useInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                         useInventoryUserKnifeInout.setInitTime(productDetails.get(0).getLifeSpan());
                         useInventoryUserKnifeInout.setRemainingTime(productDetails.get(0).getLifeSpan());
                         }
                         if (productDetails.get(0).getLifeUnit()!=null){
                         useInventoryKnife.setLifeUnit(UseInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                         useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                         }

                         }*/
                        useInventoryKnifeService.save(useInventoryKnife);

                        labelCodes.add(labelCode);

                        BeanUtils.copyProperties(useInventoryUserKnife, useInventoryUserKnifeInout);
                        useInventoryUserKnifeInout.setId(null);
                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
                        useInventoryUserKnifeInout.setCreator(creator);
                        useInventoryUserKnifeInout.setCreatorName(creatorName);
                        useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessTypeDesc());
                        useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryUserKnifeInout.setChannelCode(channelCode);
                        useInventoryUserKnifeInout.setDepartmentId(departmentId);
                        useInventoryUserKnifeInout.setDepartmentName(departmentName);
                        useInventoryUserKnifeInout.setRoleName(roleName);
                        useInventoryUserKnifeInout.setRoleId(roleId);
                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
                    }


//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);

//                    }else{
//                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();
//
//                        UseInventoryUser useInventoryUser=new UseInventoryUser();
//                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
//                        useInventoryUser.setQuantity(newQuantity);
//                        inventoryUserService.updateById(useInventoryUser);
//
//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);
//
//                    }
                } else {
                    throw new BusinessException("出入库参数类型异常");
                }

            }
        } else {
            throw new BusinessException("未提交领用/存放刀具数据");
        }
        return labelCodes;
    }

    @Transactional
    List<String> saveDetail4Loss(List<CellInventoryInoutDetailForm> list, Long inventoryInoutId, String inOutTypeName, String deviceCode, String orderCode, Long cellInventoryInoutId, Long storageInventoryInoutId, StorageInventoryInout.BusinessDetailType businessDetailType) {
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        boolean lifeFlag = false;
        if (systemRuleInfo != null) {
            lifeFlag = systemRuleInfo.getLifeFlag();
        }
        List<String> labelCodes = new ArrayList<>();
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long departmentId = JwtUtils.getDepartmentId();
        String departmentName = JwtUtils.getDepartmentName();
        String channelCode=JwtUtils.getChannelCode();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        Integer year = LocalDateTime.now().getYear();
        Integer month = LocalDateTime.now().getMonthValue();
        if (CollectionUtils.isNotEmpty(list)) {
            for (CellInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                if(null == useInventoryInoutDetailForm.getPackId() || useInventoryInoutDetailForm.getPackId().equals(0)) {
                    //useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                    //useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                    //useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                    //useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                    throw new BusinessException("请选择合适的包装方案");
                }
                //else{

                ProductPackVO productPackVO = productPackService.get4appById(useInventoryInoutDetailForm.getPackId());
                if(null != productPackVO) {
                    useInventoryInoutDetailForm.setPackId(productPackVO.getId());
                    useInventoryInoutDetailForm.setPackName(productPackVO.getName());
                    useInventoryInoutDetailForm.setUnitName(productPackVO.getPackUnitName());
                    useInventoryInoutDetailForm.setQuantityPackUnit(productPackVO.getBaseRate());
                }else{
                    useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                    useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                    useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                    useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                }
                //}
                UseInventoryInoutDetail useInventoryInoutDetail = new UseInventoryInoutDetail();
                BeanUtils.copyProperties(useInventoryInoutDetailForm, useInventoryInoutDetail);
                useInventoryInoutDetail.setId(null);
                useInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                useInventoryInoutDetail.setCreator(creator);
                useInventoryInoutDetail.setCreatorName(creatorName);
                useInventoryInoutDetail.setType(UseInventoryInoutDetail.Type.jsonCreator(inOutTypeName));
                useInventoryInoutDetail.setBusinessType(UseInventoryInoutDetail.BusinessType.jsonCreator(businessDetailType.name()));
                useInventoryInoutDetail.setInoutId(inventoryInoutId);
                useInventoryInoutDetail.setChannelCode(channelCode);
                useInventoryInoutDetail.setQuantityPack(useInventoryInoutDetailForm.getQuantity());
                //setDefaultVal(useInventoryInoutDetail);
                List<UseInventoryProduct> skuInventoryList = inventoryProductService.list(new QueryWrapper<UseInventoryProduct>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("enterprise_code", enterpriseCode));

                if (UseInventoryInout.Type.out.name().equals(inOutTypeName) ||
                        UseInventoryInout.Type.returned.name().equals(inOutTypeName)||
                        UseInventoryInout.Type.loss.name().equals(inOutTypeName)) {

                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",useInventoryInoutDetailForm.getCreator()));
//                    List<UseInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id", useInventoryInoutDetailForm.getId()));
                    List<UseInventoryKnife> skuInventoryKnifes=useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id",useInventoryInoutDetailForm.getId()));
                    if (skuInventoryKnifes.size() == 0) {
                        throw new BusinessException("未找到SKU[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品");
                    } else {
//                        List<UseInventoryKnife> skuInventoryKnifes = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("use_inventory_user_id", useInventoryInoutDetailForm.getId()));
                        for (UseInventoryKnife useInventoryKnife : skuInventoryKnifes) {

//                        List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id",skuInventoryKnifeList.get(0).getUseInventoryUserId()));

                            UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                            ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(useInventoryInoutDetailForm.getSkuCode());

                            UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();

                            if (lifeFlag && productDetailVO != null && productDetailVO.getLifeSpan() != null && productDetailVO.getLifeSpan() != 0 &&
                                    list.get(0).getUseTime() != null && list.get(0).getUseTime() != 0) {

                                KnifeLifeDetail knifeLifeDetail = new KnifeLifeDetail();
                                knifeLifeDetail.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                                knifeLifeDetail.setOutTime(useInventoryKnife.getOutTime());
                                knifeLifeDetail.setInTime(LocalDateTime.now());
                                knifeLifeDetail.setInCreator(useInventoryKnife.getCreator());
                                knifeLifeDetail.setInCreatorName(useInventoryKnife.getCreatorName());
                                knifeLifeDetail.setOutCreator(creator);
                                knifeLifeDetail.setOutCreatorName(creatorName);
                                if (useInventoryKnife.getBusinessType() != null) {
                                    knifeLifeDetail.setOutBusinessType(KnifeLifeDetail.OutBusinessType.jsonCreator(useInventoryKnife.getBusinessType().name()));
                                }
                                knifeLifeDetail.setInBusinessType(KnifeLifeDetail.InBusinessType.jsonCreator(businessDetailType.name()));
                                knifeLifeDetail.setPreTime(useInventoryKnife.getRemainingTime());
                                knifeLifeDetail.setUseTime(list.get(0).getUseTime());
                                knifeLifeDetail.setSkuCode(useInventoryKnife.getSkuCode());
                                if (productDetailVO != null) {
                                    knifeLifeDetail.setProductCode(productDetailVO.getProductCode());
                                    knifeLifeDetail.setBrandId(productDetailVO.getBrandId());
                                }
                                Integer remainingTime = 0;
                                Integer sumUsedTime = 0;
                                Integer settingTime = 0;
                                if (useInventoryKnife.getSettingTime() == null) {
                                    useInventoryKnife.setSettingTime(productDetailVO.getLifeSpan());
                                }
                                if (useInventoryKnife.getRemainingTime() == null) {
                                    remainingTime = productDetailVO.getLifeSpan() - list.get(0).getUseTime();
                                    sumUsedTime = list.get(0).getUseTime();
                                    settingTime = productDetailVO.getLifeSpan();
                                    if (productDetailVO.getLifeUnit() != null) {
                                        knifeLifeDetail.setLifeUnit(KnifeLifeDetail.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                    }
//                                StorageInventoryKnife useInventoryKnife4Update=new StorageInventoryKnife();
//                                useInventoryKnife4Update.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
//                                useInventoryKnife4Update.setRemainingTime(remainingTime);
//                                storageInventoryKnifeService.updateRemainingTime(remainingTime,useInventoryInoutDetailForm.getLabelCode());
                                } else {
                                    remainingTime = useInventoryKnife.getRemainingTime() - list.get(0).getUseTime();
                                    sumUsedTime = useInventoryKnife.getSettingTime() - remainingTime;
                                    settingTime = useInventoryKnife.getSettingTime();
                                    if (useInventoryKnife.getLifeUnit() != null) {
                                        knifeLifeDetail.setLifeUnit(KnifeLifeDetail.LifeUnit.jsonCreator(useInventoryKnife.getLifeUnit().name()));
                                    }
                                }
                                useInventoryUserKnifeInout.setUseTime(list.get(0).getUseTime());
                                useInventoryUserKnifeInout.setRemainingTime(remainingTime);
                                useInventoryUserKnifeInout.setPreTime(useInventoryKnife.getRemainingTime());
                                if (useInventoryKnife.getLifeUnit() != null) {
                                    useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(useInventoryKnife.getLifeUnit().name()));
                                }


                                storageInventoryKnifeService.updateRemainingTime(remainingTime, useInventoryInoutDetailForm.getLabelCode());

                                knifeLifeDetail.setRemainingTime(remainingTime);
                                knifeLifeDetail.setRemark(knifeLifeDetail.getInBusinessTypeDesc());
                                knifeLifeDetail.setEnterpriseCode(enterpriseCode);


                                knifeLifeDetailService.save(knifeLifeDetail);
                                useInventoryUserKnife.setUseTime(list.get(0).getUseTime());
                                useInventoryUserKnife.setRemainingTime(remainingTime);


//                            useInventoryUserKnife.setSumTime();


                                if (StorageInventoryInout.BusinessDetailType.tempIn.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.tempInByOldNew.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.repairIn.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.repairInByOldNew.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.recycleIn.equals(businessDetailType) ||
                                        StorageInventoryInout.BusinessDetailType.recycleInByOldNew.equals(businessDetailType)
                                ) {
                                    List<SkuLife> skuLives = skuLifeService.list(new QueryWrapper<SkuLife>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("year", year).eq("month", month).eq("enterprise_code", enterpriseCode));

                                    if (skuLives.size() > 0) {
                                        SkuLife skuLife = skuLives.get(0);
                                        if (UseInventoryKnife.BusinessType.cellCabOut.equals(useInventoryKnife.getBusinessType()) ||
                                                UseInventoryKnife.BusinessType.cellCabOutByOldNew.equals(useInventoryKnife.getBusinessType())) {
                                            skuLife.setQuantity(skuLives.get(0).getQuantity() + 1);
                                        }
                                        skuLife.setSumTime(skuLives.get(0).getSumTime() + list.get(0).getUseTime());
                                        skuLife.setId(skuLives.get(0).getId());
                                        skuLifeService.updateById(skuLife);
                                    } else {
                                        SkuLife skuLife = new SkuLife();
                                        skuLife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                                        skuLife.setSumTime(list.get(0).getUseTime());
                                        skuLife.setQuantity(1);
                                        skuLife.setProductCode(productDetailVO.getProductCode());
                                        skuLife.setBrandId(productDetailVO.getBrandId());
                                        skuLife.setSettingTime(productDetailVO.getLifeSpan());
                                        if (productDetailVO.getLifeUnit() != null) {
                                            skuLife.setLifeUnit(SkuLife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                        }

                                        skuLife.setEnterpriseCode(enterpriseCode);
                                        skuLife.setYear(year);
                                        skuLife.setMonth(month);
                                        skuLifeService.save(skuLife);
                                    }
                                    if (productDetailVO.getBrandId() != null) {
                                        if (StorageInventoryInout.BusinessDetailType.repairIn.equals(businessDetailType) ||
                                                StorageInventoryInout.BusinessDetailType.repairInByOldNew.equals(businessDetailType) ||
                                                StorageInventoryInout.BusinessDetailType.recycleIn.equals(businessDetailType) ||
                                                StorageInventoryInout.BusinessDetailType.recycleInByOldNew.equals(businessDetailType)) {

                                            if (settingTime != null && sumUsedTime != null && settingTime != 0) {
                                                BigDecimal lifeRate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);
                                                String lifeRateStr = new DecimalFormat("0.0000").format(lifeRate);
                                                useInventoryUserKnife.setRate(BigDecimal.valueOf(Double.valueOf(lifeRateStr)));
                                            }

                                            List<BrandLife> brandLives = brandLifeService.list(new QueryWrapper<BrandLife>().eq("brand_id", productDetailVO.getBrandId()).eq("year", year).eq("month", month).eq("enterprise_code", enterpriseCode));
//                                        Integer sumUsedTime=productDetailVO.getLifeSpan()-remainingTime;
                                            if (sumUsedTime != null && sumUsedTime != null && settingTime.doubleValue() != 0) {
                                                if (brandLives.size() > 0) {

                                                    BrandLife brandLife = brandLives.get(0);
                                                    brandLife.setId(brandLives.get(0).getId());
                                                    BigDecimal lifeRate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);

                                                    if (brandLives.get(0).getSumRate() == null) {
                                                        brandLives.get(0).setSumRate(BigDecimal.valueOf(0));
                                                    }
                                                    if (brandLives.get(0).getQuantity() == null) {
                                                        brandLives.get(0).setQuantity(0);
                                                    }
                                                    if (brandLives.get(0).getUseTime() == null) {
                                                        brandLives.get(0).setUseTime(0);
                                                    }
                                                    if (brandLives.get(0).getSumTime() == null) {
                                                        brandLives.get(0).setSumTime(0);
                                                    }
                                                    BigDecimal sumRate = lifeRate.add(brandLives.get(0).getSumRate());
                                                    BigDecimal avgRate = sumRate.divide(BigDecimal.valueOf(brandLives.get(0).getQuantity() + 1), mathContext);
                                                    DecimalFormat df = new DecimalFormat("0.0000");
                                                    String avgRateVal = df.format(avgRate.doubleValue());
                                                    brandLife.setRate(BigDecimal.valueOf(Double.valueOf(avgRateVal)));
                                                    brandLife.setSumRate(sumRate);
                                                    brandLife.setUseTime(brandLives.get(0).getUseTime() + sumUsedTime);
                                                    brandLife.setSumTime(brandLives.get(0).getSumTime() + settingTime);
                                                    brandLife.setQuantity(brandLives.get(0).getQuantity() + 1);
                                                    brandLifeService.updateById(brandLife);


                                                } else {
                                                    BrandLife brandLife = new BrandLife();
                                                    brandLife.setBrandId(productDetailVO.getBrandId());
                                                    brandLife.setUseTime(sumUsedTime);
                                                    brandLife.setSumTime(settingTime);
                                                    BigDecimal rate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);
                                                    DecimalFormat df = new DecimalFormat("0.0000");
                                                    String rateVal = df.format(rate.doubleValue());
                                                    brandLife.setRate(BigDecimal.valueOf(Double.valueOf(rateVal)));
                                                    brandLife.setSumRate(brandLife.getRate());
                                                    brandLife.setEnterpriseCode(enterpriseCode);
                                                    brandLife.setYear(year);
                                                    brandLife.setMonth(month);
                                                    brandLife.setQuantity(1);
                                                    if (productDetailVO.getLifeUnit() != null) {
                                                        brandLife.setLifeUnit(BrandLife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                                    }

                                                    brandLifeService.save(brandLife);
                                                }
                                            }

                                        }

                                    }
                                }


                            }


                            useInventoryKnifeService.remove(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryKnife.getId()));

                            if (UseInventoryInout.Type.out.name().equals(inOutTypeName)) {
                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
                                useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
                            }else if(UseInventoryInout.Type.returned.name().equals(inOutTypeName)){
                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.returned);
                                useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.returned);
                            }else if(UseInventoryInout.Type.loss.name().equals(inOutTypeName)){
                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.loss);
                                useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.loss);
                            }

                            useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                            useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                            useInventoryUserKnife.setInTime(LocalDateTime.now());
                            useInventoryUserKnife.setCode(useInventoryKnife.getLabelCode());
                            useInventoryUserKnife.setCategoryId(useInventoryInoutDetailForm.getCategoryId());
//                        useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
                            useInventoryUserKnifeService.updateKnife(useInventoryUserKnife);


                            useInventoryUserKnifeInout.setCode(useInventoryKnife.getLabelCode());
                            useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            useInventoryUserKnifeInout.setUseInventoryUserId(useInventoryKnife.getUseInventoryUserId());
                            useInventoryUserKnifeInout.setUseInventoryInoutId(inventoryInoutId);
                            useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
//                        useInventoryUserKnifeInout.setCellInventoryInoutId(cellInventoryInoutId);
                            useInventoryUserKnifeInout.setDeviceCode(deviceCode);

                            useInventoryUserKnifeInout.setCreator(creator);
                            useInventoryUserKnifeInout.setCreatorName(creatorName);
                            useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                            useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessType() != null ? useInventoryUserKnifeInout.getBusinessType().getDesc() : "");
                            useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                            useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                            useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                            useInventoryUserKnifeInout.setCategoryId(useInventoryInoutDetailForm.getCategoryId());
                            useInventoryUserKnifeInout.setChannelCode(channelCode);
                            useInventoryUserKnifeInout.setDepartmentId(departmentId);
                            useInventoryUserKnifeInout.setDepartmentName(departmentName);
                            useInventoryUserKnifeInout.setRoleName(roleName);
                            useInventoryUserKnifeInout.setRoleId(roleId);
                            useInventoryUserKnifeInout.setChannelCode(channelCode);
                            useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);

                        }
                    }
                    Integer quantity = useInventoryInoutDetailForm.getQuantity();
                    if (quantity > 0) {
                        quantity = -1 * quantity;
                    }
                    if (skuInventoryUserList.size() > 0) {
                        Integer currentQuantity = skuInventoryUserList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                                throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                        }

                        UseInventoryUser useInventoryUser = new UseInventoryUser();
                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUser.setQuantity(newQuantity);
                        if (newQuantity <= 0) {
                            inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                        } else {
                            inventoryUserService.updateById(useInventoryUser);
                        }

                        if (skuInventoryList.size() > 0) {
                            useInventoryInoutDetail.setQuantityCurrent(skuInventoryList.get(0).getQuantity());
                            useInventoryInoutDetail.setQuantityAfter(skuInventoryList.get(0).getQuantity() + quantity);
                        } else {
                            useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                            useInventoryInoutDetail.setQuantityAfter(newQuantity);
                        }
                    }

//                        if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getLabelCode())){
//                            UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                            useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                            useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
//                        }else{
//                            List<UseInventoryUserKnife> useInventoryUserKnives=useInventoryUserKnifeService.list(new QueryWrapper<UseInventoryUserKnife>().eq("use_inventory_user_id",useInventoryInoutDetailForm.getId()).eq("status",UseInventoryUserKnife.Status.used.getValue()));
//                            int size=useInventoryUserKnives.size();
//                            if (size>useInventoryInoutDetailForm.getQuantity()){
//                                size=useInventoryInoutDetailForm.getQuantity();
//                            }
//                            for (int i=0;i<size;i++){
//                                UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                                useInventoryUserKnife.setId(useInventoryUserKnives.get(i).getId());
//                                useInventoryUserKnifeService.updateById(useInventoryUserKnife);
//                            }
//                        }


                    useInventoryInoutDetail.setQuantity(quantity);
                    useInventoryInoutDetail.setCreator(useInventoryInoutDetailForm.getCreator());
                    useInventoryInoutDetail.setCreatorName(useInventoryInoutDetailForm.getCreatorName());
                    useInventoryInoutDetail.setModifier(creator);
                    useInventoryInoutDetail.setModifierName(creatorName);
                    baseMapper.insert(useInventoryInoutDetail);


//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException("未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
//                    }else{
                    if (skuInventoryList.size() > 0) {


                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                            throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                            newQuantity = 0;
                        }

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        if (newQuantity <= 0) {
                            inventoryProductService.removeById(skuInventoryList.get(0).getId());
                        } else {
                            inventoryProductService.updateById(useInventoryProduct);
                        }


//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(useInventoryInoutDetail);
                    }

//                    }
                } else if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",creator));

//                    Integer quantity=useInventoryInoutDetailForm.getQuantity();
                    List<ProductDetail> productDetails = productDetailService.list(new QueryWrapper<ProductDetail>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()));
                    if (useInventoryInoutDetailForm.getQuantity() < 0) {
                        throw new BusinessException("领取数量参数异常");
                    }
                    if (skuInventoryList.size() == 0) {
                        Integer currentQuantity = 0;
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        useInventoryProduct.setDeviceCode(deviceCode);
                        useInventoryProduct.setEnterpriseCode(enterpriseCode);
                        useInventoryProduct.setCreator(creator);
                        useInventoryProduct.setCreatorName(creatorName);
                        useInventoryProduct.setEnterpriseCode(enterpriseCode);
                        useInventoryProduct.setChannelCode(channelCode);
                        inventoryProductService.save(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        baseMapper.insert(useInventoryInoutDetail);
                    } else {

                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        inventoryProductService.updateById(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                        baseMapper.insert(useInventoryInoutDetail);
                    }
//                    quantity=useInventoryInoutDetailForm.getQuantity();
//                    if (skuInventoryUserList.size()==0){
//                        Integer currentQuantity=0;
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                    UseInventoryUser useInventoryUser = new UseInventoryUser();
                    useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    useInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    useInventoryUser.setCreator(creator);
                    useInventoryUser.setCreatorName(creatorName);
                    useInventoryUser.setDeviceCode(deviceCode);
                    useInventoryUser.setOrderCode(orderCode);
                    useInventoryUser.setCellInventoryInoutId(cellInventoryInoutId);
                    useInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    useInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    useInventoryUser.setUseInventoryInoutId(inventoryInoutId);
                    useInventoryUser.setUseInventoryInoutDetailId(useInventoryInoutDetail.getId());
                    useInventoryUser.setWorkOrderId(list.get(0).getWorkOrderId());
                    useInventoryUser.setDepartmentId(departmentId);
                    useInventoryUser.setDepartmentName(departmentName);
                    useInventoryUser.setEnterpriseCode(enterpriseCode);
                    useInventoryUser.setBusinessType(UseInventoryUser.BusinessType.jsonCreator(businessDetailType.name()));
                    useInventoryUser.setRemark(useInventoryUser.getBusinessTypeDesc());
                    useInventoryUser.setChannelCode(channelCode);
                    useInventoryUser.setRoleName(roleName);
                    useInventoryUser.setRoleId(roleId);
                    inventoryUserService.save(useInventoryUser);

                    for (int i = 0; i < useInventoryInoutDetailForm.getQuantity(); i++) {
                        UseInventoryUserKnifeSeq useInventoryUserKnifeSeq = new UseInventoryUserKnifeSeq();
                        useInventoryUserKnifeSeqService.insert(useInventoryUserKnifeSeq);
                        Long labelId = useInventoryUserKnifeSeqService.getId();
                        String labelCode = StringUtils.leftPad(labelId.toString(), 10, "0");
                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                        useInventoryUserKnife.setCode(labelCode);
                        useInventoryUserKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUserKnife.setUseInventoryUserId(useInventoryUser.getId());
                        useInventoryUserKnife.setUseInventoryInoutId(inventoryInoutId);
                        useInventoryUserKnife.setCellInventoryInoutId(cellInventoryInoutId);
                        useInventoryUserKnife.setDeviceCode(deviceCode);
                        useInventoryUserKnife.setCreator(creator);
                        useInventoryUserKnife.setCreatorName(creatorName);
                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                        useInventoryUserKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnife.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryUserKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryUserKnife.setOutTime(LocalDateTime.now());
                        useInventoryUserKnife.setChannelCode(channelCode);
                        useInventoryUserKnife.setDepartmentId(departmentId);
                        useInventoryUserKnife.setDepartmentName(departmentName);
                        useInventoryUserKnife.setRoleId(roleId);
                        useInventoryUserKnife.setRoleName(roleName);

                        UseInventoryKnife useInventoryKnife = new UseInventoryKnife();
                        UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();

                        if (productDetails.size() > 0) {
                            if (productDetails.get(0).getLifeSpan() != null) {
                                useInventoryUserKnife.setInitTime(productDetails.get(0).getLifeSpan());
                                useInventoryUserKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                useInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                useInventoryKnife.setSettingTime(productDetails.get(0).getLifeSpan());

                                useInventoryUserKnifeInout.setInitTime(productDetails.get(0).getLifeSpan());
                                useInventoryUserKnifeInout.setRemainingTime(productDetails.get(0).getLifeSpan());
                            }

                            if (productDetails.get(0).getLifeUnit() != null) {
                                useInventoryKnife.setLifeUnit(UseInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                useInventoryUserKnife.setLifeUnit(UseInventoryUserKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                            }

                        }
                        useInventoryUserKnifeService.save(useInventoryUserKnife);


                        useInventoryKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryKnife.setQuantity(1);
                        useInventoryKnife.setCreator(creator);
                        useInventoryKnife.setCreatorName(creatorName);
                        useInventoryKnife.setDeviceCode(deviceCode);
                        useInventoryKnife.setOrderCode(orderCode);
                        useInventoryKnife.setCellInventoryInoutId(cellInventoryInoutId);
                        useInventoryKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryKnife.setUseInventoryInoutId(inventoryInoutId);
                        useInventoryKnife.setUseInventoryInoutDetailId(useInventoryInoutDetail.getId());
                        useInventoryKnife.setLabelCode(labelCode);
                        useInventoryKnife.setUseInventoryUserId(useInventoryUser.getId());
                        useInventoryKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryKnife.setEnterpriseCode(enterpriseCode);
                        useInventoryKnife.setOutTime(LocalDateTime.now());
                        useInventoryKnife.setBusinessType(UseInventoryKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryKnife.setRemark(useInventoryKnife.getBusinessTypeDesc());
                        useInventoryKnife.setChannelCode(channelCode);
                        useInventoryKnife.setDepartmentId(departmentId);
                        useInventoryKnife.setDepartmentName(departmentName);
                        useInventoryKnife.setRoleId(roleId);
                        useInventoryKnife.setRoleName(roleName);
                        useInventoryKnife.setPackId(useInventoryInoutDetailForm.getPackId());
                        useInventoryKnife.setPackName(useInventoryInoutDetailForm.getPackName());

                        /**
                         if (productDetails.size()>0){
                         if (productDetails.get(0).getLifeSpan()!=null){
                         useInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                         useInventoryUserKnifeInout.setInitTime(productDetails.get(0).getLifeSpan());
                         useInventoryUserKnifeInout.setRemainingTime(productDetails.get(0).getLifeSpan());
                         }
                         if (productDetails.get(0).getLifeUnit()!=null){
                         useInventoryKnife.setLifeUnit(UseInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                         useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                         }

                         }*/
                        useInventoryKnifeService.save(useInventoryKnife);

                        labelCodes.add(labelCode);

                        BeanUtils.copyProperties(useInventoryUserKnife, useInventoryUserKnifeInout);
                        useInventoryUserKnifeInout.setId(null);
                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
                        useInventoryUserKnifeInout.setCreator(creator);
                        useInventoryUserKnifeInout.setCreatorName(creatorName);
                        useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessTypeDesc());
                        useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryUserKnifeInout.setChannelCode(channelCode);
                        useInventoryUserKnifeInout.setDepartmentName(departmentName);
                        useInventoryUserKnifeInout.setDepartmentId(departmentId);
                        useInventoryUserKnifeInout.setRoleId(roleId);
                        useInventoryUserKnifeInout.setRoleName(roleName);

                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
                    }


//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);

//                    }else{
//                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();
//
//                        UseInventoryUser useInventoryUser=new UseInventoryUser();
//                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
//                        useInventoryUser.setQuantity(newQuantity);
//                        inventoryUserService.updateById(useInventoryUser);
//
//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);
//
//                    }
                } else {
                    throw new BusinessException("出入库参数类型异常");
                }

            }
        } else {
            throw new BusinessException("未提交领用/存放刀具数据");
        }
        return labelCodes;
    }

    @Transactional
    List<String> saveDetail(List<CellInventoryInoutDetailForm> list, Long inventoryInoutId, String inOutTypeName, String deviceCode, String orderCode, Long cellInventoryInoutId, Long storageInventoryInoutId, StorageInventoryInout.BusinessDetailType businessDetailType) {
        log.info("进入saveDetail接受参数cellInventoryInoutId："+cellInventoryInoutId);
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        boolean lifeFlag = false;
        if (systemRuleInfo != null) {
            lifeFlag = systemRuleInfo.getLifeFlag();
        }
        List<String> labelCodes = new ArrayList<>();
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long departmentId = JwtUtils.getDepartmentId();
        String departmentName = JwtUtils.getDepartmentName();
        String channelCode=JwtUtils.getChannelCode();
        Long roleId=JwtUtils.getRoleId();
        String roleName=JwtUtils.getRoleName();
        Integer year = LocalDateTime.now().getYear();
        Integer month = LocalDateTime.now().getMonthValue();
        if (CollectionUtils.isNotEmpty(list)) {
            for (CellInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getDeviceCode())){
                    deviceCode=useInventoryInoutDetailForm.getDeviceCode();
                }

                if(null == useInventoryInoutDetailForm.getPackId() || useInventoryInoutDetailForm.getPackId().equals(0)) {
                    //useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                    //useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                    //useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                    //useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                    throw new BusinessException("请选择合适的包装方案");
                }
                //else{
                    ProductPackVO productPackVO =productPackService.get4appById(useInventoryInoutDetailForm.getPackId());
                    if(null != productPackVO) {
                        useInventoryInoutDetailForm.setPackId(productPackVO.getId());
                        useInventoryInoutDetailForm.setPackName(productPackVO.getName());
                        useInventoryInoutDetailForm.setUnitName(productPackVO.getPackUnitName());
                        useInventoryInoutDetailForm.setQuantityPackUnit(productPackVO.getBaseRate());
                    }else{
                        useInventoryInoutDetailForm.setPackId(CabConstants.DEFAULT_PACK_ID);
                        useInventoryInoutDetailForm.setPackName(CabConstants.DEFAULT_PACK_NAME);
                        useInventoryInoutDetailForm.setUnitName(CabConstants.DEFAULT_UNIT_NAME);
                        useInventoryInoutDetailForm.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
                    }
               // }

                UseInventoryInoutDetail useInventoryInoutDetail = new UseInventoryInoutDetail();
                BeanUtils.copyProperties(useInventoryInoutDetailForm, useInventoryInoutDetail);
                useInventoryInoutDetail.setId(null);
                useInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                useInventoryInoutDetail.setCreator(creator);
                useInventoryInoutDetail.setCreatorName(creatorName);
                useInventoryInoutDetail.setType(UseInventoryInoutDetail.Type.jsonCreator(inOutTypeName));
                useInventoryInoutDetail.setBusinessType(UseInventoryInoutDetail.BusinessType.jsonCreator(businessDetailType.name()));
                useInventoryInoutDetail.setInoutId(inventoryInoutId);
                useInventoryInoutDetail.setChannelCode(channelCode);
                useInventoryInoutDetail.setQuantityPack(useInventoryInoutDetailForm.getQuantity());
                useInventoryInoutDetail.setMainCabCode(useInventoryInoutDetailForm.getMainCabCode());

                List<UseInventoryProduct> skuInventoryList = inventoryProductService.list(new QueryWrapper<UseInventoryProduct>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("enterprise_code", enterpriseCode));

                if (UseInventoryInout.Type.out.name().equals(inOutTypeName) ||
                        UseInventoryInout.Type.returned.name().equals(inOutTypeName)) {

//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",useInventoryInoutDetailForm.getCreator()));
//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));
                    List<UseInventoryKnife> skuInventoryKnifeList = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                    if (skuInventoryKnifeList.size() == 0) {
                        throw new BusinessException("未找到SKU[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品");
                    } else {
                        List<UseInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id", skuInventoryKnifeList.get(0).getUseInventoryUserId()));
                        if (skuInventoryUserList.size() == 0) {
//                            throw new BusinessException("未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
                        }
                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                        ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(useInventoryInoutDetailForm.getSkuCode());
                        BigDecimal price=skuInventoryKnifeList.get(0).getPrice();
                        BigDecimal total=null;
                        if (price!=null){
                            total=price.multiply(BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()));
                        }
                        useInventoryInoutDetail.setPrice(price);
                        useInventoryInoutDetail.setTotal(total);

                        UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();

                        if (lifeFlag && productDetailVO != null && productDetailVO.getLifeSpan() != null && productDetailVO.getLifeSpan() != 0 &&
                                list.get(0).getUseTime() != null && list.get(0).getUseTime() != 0) {

                            KnifeLifeDetail knifeLifeDetail = new KnifeLifeDetail();
                            knifeLifeDetail.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                            knifeLifeDetail.setOutTime(skuInventoryKnifeList.get(0).getOutTime());
                            knifeLifeDetail.setInTime(LocalDateTime.now());
                            knifeLifeDetail.setInCreator(skuInventoryKnifeList.get(0).getCreator());
                            knifeLifeDetail.setInCreatorName(skuInventoryKnifeList.get(0).getCreatorName());
                            knifeLifeDetail.setOutCreator(creator);
                            knifeLifeDetail.setOutCreatorName(creatorName);
                            if (skuInventoryKnifeList.get(0).getBusinessType() != null) {
                                knifeLifeDetail.setOutBusinessType(KnifeLifeDetail.OutBusinessType.jsonCreator(skuInventoryKnifeList.get(0).getBusinessType().name()));
                            }
                            knifeLifeDetail.setInBusinessType(KnifeLifeDetail.InBusinessType.jsonCreator(businessDetailType.name()));
                            knifeLifeDetail.setPreTime(skuInventoryKnifeList.get(0).getRemainingTime());
                            knifeLifeDetail.setUseTime(list.get(0).getUseTime());
                            knifeLifeDetail.setSkuCode(skuInventoryKnifeList.get(0).getSkuCode());
                            if (productDetailVO != null) {
                                knifeLifeDetail.setProductCode(productDetailVO.getProductCode());
                                knifeLifeDetail.setBrandId(productDetailVO.getBrandId());
                            }
                            Integer remainingTime = 0;
                            Integer sumUsedTime = 0;
                            Integer settingTime = 0;
                            if (skuInventoryKnifeList.get(0).getSettingTime() == null) {
                                skuInventoryKnifeList.get(0).setSettingTime(productDetailVO.getLifeSpan());
                            }
                            if (skuInventoryKnifeList.get(0).getRemainingTime() == null) {
                                remainingTime = productDetailVO.getLifeSpan() - list.get(0).getUseTime();
                                sumUsedTime = list.get(0).getUseTime();
                                settingTime = productDetailVO.getLifeSpan();
                                if (productDetailVO.getLifeUnit() != null) {
                                    knifeLifeDetail.setLifeUnit(KnifeLifeDetail.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                }
//                                StorageInventoryKnife useInventoryKnife4Update=new StorageInventoryKnife();
//                                useInventoryKnife4Update.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
//                                useInventoryKnife4Update.setRemainingTime(remainingTime);
//                                storageInventoryKnifeService.updateRemainingTime(remainingTime,useInventoryInoutDetailForm.getLabelCode());
                            } else {
                                remainingTime = skuInventoryKnifeList.get(0).getRemainingTime() - list.get(0).getUseTime();
                                sumUsedTime = skuInventoryKnifeList.get(0).getSettingTime() - remainingTime;
                                settingTime = skuInventoryKnifeList.get(0).getSettingTime();
                                if (skuInventoryKnifeList.get(0).getLifeUnit() != null) {
                                    knifeLifeDetail.setLifeUnit(KnifeLifeDetail.LifeUnit.jsonCreator(skuInventoryKnifeList.get(0).getLifeUnit().name()));
                                }
                            }
                            useInventoryUserKnifeInout.setUseTime(list.get(0).getUseTime());
                            useInventoryUserKnifeInout.setRemainingTime(remainingTime);
                            useInventoryUserKnifeInout.setPreTime(skuInventoryKnifeList.get(0).getRemainingTime());
                            if (skuInventoryKnifeList.get(0).getLifeUnit() != null) {
                                useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(skuInventoryKnifeList.get(0).getLifeUnit().name()));
                            }


//                            storageInventoryKnifeService.updateRemainingTime(remainingTime, useInventoryInoutDetailForm.getLabelCode());

                            knifeLifeDetail.setRemainingTime(remainingTime);
                            knifeLifeDetail.setRemark(knifeLifeDetail.getInBusinessTypeDesc());
                            knifeLifeDetail.setEnterpriseCode(enterpriseCode);


                            knifeLifeDetailService.save(knifeLifeDetail);
                            useInventoryUserKnife.setUseTime(list.get(0).getUseTime());
                            useInventoryUserKnife.setRemainingTime(remainingTime);


//                            useInventoryUserKnife.setSumTime();


                            if (StorageInventoryInout.BusinessDetailType.tempIn.equals(businessDetailType) ||
                                    StorageInventoryInout.BusinessDetailType.tempInByOldNew.equals(businessDetailType) ||
                                    StorageInventoryInout.BusinessDetailType.repairIn.equals(businessDetailType) ||
                                    StorageInventoryInout.BusinessDetailType.repairInByOldNew.equals(businessDetailType) ||
                                    StorageInventoryInout.BusinessDetailType.recycleIn.equals(businessDetailType) ||
                                    StorageInventoryInout.BusinessDetailType.recycleInByOldNew.equals(businessDetailType)
                            ) {
                                List<SkuLife> skuLives = skuLifeService.list(new QueryWrapper<SkuLife>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("year", year).eq("month", month).eq("enterprise_code", enterpriseCode));

                                if (skuLives.size() > 0) {
                                    SkuLife skuLife = skuLives.get(0);
                                    if (UseInventoryKnife.BusinessType.cellCabOut.equals(skuInventoryKnifeList.get(0).getBusinessType()) ||
                                            UseInventoryKnife.BusinessType.cellCabOutByOldNew.equals(skuInventoryKnifeList.get(0).getBusinessType())) {
                                        skuLife.setQuantity(skuLives.get(0).getQuantity() + 1);
                                    }
                                    skuLife.setSumTime(skuLives.get(0).getSumTime() + list.get(0).getUseTime());
                                    skuLife.setId(skuLives.get(0).getId());
                                    skuLifeService.updateById(skuLife);
                                } else {
                                    SkuLife skuLife = new SkuLife();
                                    skuLife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                                    skuLife.setSumTime(list.get(0).getUseTime());
                                    skuLife.setQuantity(1);
                                    skuLife.setProductCode(productDetailVO.getProductCode());
                                    skuLife.setBrandId(productDetailVO.getBrandId());
                                    skuLife.setSettingTime(productDetailVO.getLifeSpan());
                                    if (productDetailVO.getLifeUnit() != null) {
                                        skuLife.setLifeUnit(SkuLife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                    }

                                    skuLife.setEnterpriseCode(enterpriseCode);
                                    skuLife.setYear(year);
                                    skuLife.setMonth(month);
                                    skuLifeService.save(skuLife);
                                }
                                if (productDetailVO.getBrandId() != null) {
                                    if (StorageInventoryInout.BusinessDetailType.repairIn.equals(businessDetailType) ||
                                            StorageInventoryInout.BusinessDetailType.repairInByOldNew.equals(businessDetailType) ||
                                            StorageInventoryInout.BusinessDetailType.recycleIn.equals(businessDetailType) ||
                                            StorageInventoryInout.BusinessDetailType.recycleInByOldNew.equals(businessDetailType)) {

                                        if (settingTime != null && sumUsedTime != null && settingTime != 0) {
                                            BigDecimal lifeRate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);
                                            String lifeRateStr = new DecimalFormat("0.0000").format(lifeRate);
                                            useInventoryUserKnife.setRate(BigDecimal.valueOf(Double.valueOf(lifeRateStr)));
                                        }

                                        List<BrandLife> brandLives = brandLifeService.list(new QueryWrapper<BrandLife>().eq("brand_id", productDetailVO.getBrandId()).eq("year", year).eq("month", month).eq("enterprise_code", enterpriseCode));
//                                        Integer sumUsedTime=productDetailVO.getLifeSpan()-remainingTime;
                                        if (sumUsedTime != null && sumUsedTime != null && settingTime.doubleValue() != 0) {
                                            if (brandLives.size() > 0) {

                                                BrandLife brandLife = brandLives.get(0);
                                                brandLife.setId(brandLives.get(0).getId());
                                                BigDecimal lifeRate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);

                                                if (brandLives.get(0).getSumRate() == null) {
                                                    brandLives.get(0).setSumRate(BigDecimal.valueOf(0));
                                                }
                                                if (brandLives.get(0).getQuantity() == null) {
                                                    brandLives.get(0).setQuantity(0);
                                                }
                                                if (brandLives.get(0).getUseTime() == null) {
                                                    brandLives.get(0).setUseTime(0);
                                                }
                                                if (brandLives.get(0).getSumTime() == null) {
                                                    brandLives.get(0).setSumTime(0);
                                                }
                                                BigDecimal sumRate = lifeRate.add(brandLives.get(0).getSumRate());
                                                BigDecimal avgRate = sumRate.divide(BigDecimal.valueOf(brandLives.get(0).getQuantity() + 1), mathContext);
                                                DecimalFormat df = new DecimalFormat("0.0000");
                                                String avgRateVal = df.format(avgRate.doubleValue());
                                                brandLife.setRate(BigDecimal.valueOf(Double.valueOf(avgRateVal)));
                                                brandLife.setSumRate(sumRate);
                                                brandLife.setUseTime(brandLives.get(0).getUseTime() + sumUsedTime);
                                                brandLife.setSumTime(brandLives.get(0).getSumTime() + settingTime);
                                                brandLife.setQuantity(brandLives.get(0).getQuantity() + 1);
                                                brandLifeService.updateById(brandLife);


                                            } else {
                                                BrandLife brandLife = new BrandLife();
                                                brandLife.setBrandId(productDetailVO.getBrandId());
                                                brandLife.setUseTime(sumUsedTime);
                                                brandLife.setSumTime(settingTime);
                                                BigDecimal rate = BigDecimal.valueOf(sumUsedTime).divide(BigDecimal.valueOf(settingTime), mathContext);
                                                DecimalFormat df = new DecimalFormat("0.0000");
                                                String rateVal = df.format(rate.doubleValue());
                                                brandLife.setRate(BigDecimal.valueOf(Double.valueOf(rateVal)));
                                                brandLife.setSumRate(brandLife.getRate());
                                                brandLife.setEnterpriseCode(enterpriseCode);
                                                brandLife.setYear(year);
                                                brandLife.setMonth(month);
                                                brandLife.setQuantity(1);
                                                if (productDetailVO.getLifeUnit() != null) {
                                                    brandLife.setLifeUnit(BrandLife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                                                }

                                                brandLifeService.save(brandLife);
                                            }
                                        }

                                    }

                                }
                            }


                        }


                        useInventoryKnifeService.remove(new QueryWrapper<UseInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));

                        if (UseInventoryInout.Type.out.name().equals(inOutTypeName)) {
                            useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
                            useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
                        }else if(UseInventoryInout.Type.returned.name().equals(inOutTypeName)){
                            useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.returned);
                            useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.returned);
                        }
                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                        useInventoryUserKnife.setInTime(LocalDateTime.now());
                        useInventoryUserKnife.setCode(useInventoryInoutDetailForm.getLabelCode());
                        useInventoryUserKnife.setCategoryId(useInventoryInoutDetailForm.getCategoryId());

//                        useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
                        useInventoryUserKnifeService.updateKnife(useInventoryUserKnife);


                        useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
                        useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUserKnifeInout.setUseInventoryUserId(skuInventoryKnifeList.get(0).getUseInventoryUserId());
                        useInventoryUserKnifeInout.setUseInventoryInoutId(inventoryInoutId);
                        useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
//                        useInventoryUserKnifeInout.setCellInventoryInoutId(cellInventoryInoutId);
                        useInventoryUserKnifeInout.setDeviceCode(deviceCode);

                        useInventoryUserKnifeInout.setCreator(creator);
                        useInventoryUserKnifeInout.setCreatorName(creatorName);
                        useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessType() != null ? useInventoryUserKnifeInout.getBusinessType().getDesc() : "");
                        useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnifeInout.setProcessId(list.get(0).getProcessId());
                        useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryUserKnifeInout.setCategoryId(useInventoryInoutDetailForm.getCategoryId());
                        useInventoryUserKnifeInout.setChannelCode(channelCode);
                        useInventoryUserKnifeInout.setDepartmentId(departmentId);
                        useInventoryUserKnifeInout.setDepartmentName(departmentName);
                        useInventoryUserKnifeInout.setRoleId(roleId);
                        useInventoryUserKnifeInout.setRoleName(roleName);
                        useInventoryUserKnifeInout.setPrice(price);
                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);


                        Integer quantity = useInventoryInoutDetailForm.getQuantity();
                        if (quantity > 0) {
                            quantity = -1 * quantity;
                        }
                        if (skuInventoryUserList.size() > 0) {
                            Integer currentQuantity = skuInventoryUserList.get(0).getQuantity();
                            Integer newQuantity = currentQuantity + quantity;
                            if (newQuantity < 0) {
//                                throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                            }

                            UseInventoryUser useInventoryUser = new UseInventoryUser();
                            useInventoryUser.setId(skuInventoryKnifeList.get(0).getUseInventoryUserId());
//                        useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            useInventoryUser.setQuantity(newQuantity);
                            if (newQuantity <= 0) {
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            } else {
                                List<ProductDetail> productDetails = productDetailService.listBySkuCode(useInventoryInoutDetailForm.getSkuCode());
                                useInventoryUser.setTotal(productDetails.get(0).getBasePrice().multiply(BigDecimal.valueOf(newQuantity)));
                                inventoryUserService.updateById(useInventoryUser);
                            }
                            useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                            useInventoryInoutDetail.setQuantityAfter(currentQuantity + quantity);
                            /**
                            if (skuInventoryList.size() > 0) {
                                useInventoryInoutDetail.setQuantityCurrent(skuInventoryList.get(0).getQuantity());
                                useInventoryInoutDetail.setQuantityAfter(skuInventoryList.get(0).getQuantity() + quantity);
                            } else {
                                useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                                useInventoryInoutDetail.setQuantityAfter(newQuantity);
                            }*/
                        }

//                        if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getLabelCode())){
//                            UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                            useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                            useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
//                        }else{
//                            List<UseInventoryUserKnife> useInventoryUserKnives=useInventoryUserKnifeService.list(new QueryWrapper<UseInventoryUserKnife>().eq("use_inventory_user_id",useInventoryInoutDetailForm.getId()).eq("status",UseInventoryUserKnife.Status.used.getValue()));
//                            int size=useInventoryUserKnives.size();
//                            if (size>useInventoryInoutDetailForm.getQuantity()){
//                                size=useInventoryInoutDetailForm.getQuantity();
//                            }
//                            for (int i=0;i<size;i++){
//                                UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
//                                useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
//                                useInventoryUserKnife.setId(useInventoryUserKnives.get(i).getId());
//                                useInventoryUserKnifeService.updateById(useInventoryUserKnife);
//                            }
//                        }


                        useInventoryInoutDetail.setQuantity(quantity);
                        useInventoryInoutDetail.setCreator(useInventoryInoutDetailForm.getCreator());
                        useInventoryInoutDetail.setCreatorName(useInventoryInoutDetailForm.getCreatorName());
                        useInventoryInoutDetail.setModifier(creator);
                        useInventoryInoutDetail.setModifierName(creatorName);
//                        baseMapper.insert(useInventoryInoutDetail);
                    }


//                    if (skuInventoryList.size()==0){
//                        throw new BusinessException("未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
//                    }else{
                    if (skuInventoryList.size() > 0) {
                        Integer quantity = useInventoryInoutDetailForm.getQuantity();
                        if (quantity > 0) {
                            quantity = -1 * quantity;
                        }

                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                            throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                            newQuantity = 0;
                        }

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        if (newQuantity <= 0) {
                            inventoryProductService.removeById(skuInventoryList.get(0).getId());
                        } else {
                            inventoryProductService.updateById(useInventoryProduct);
                        }
                        useInventoryInoutDetail.setQuantityProductCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityProductAfter(currentQuantity + quantity);
                        useInventoryInoutDetail.setMainCabCode(useInventoryInoutDetailForm.getMainCabCode());

//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(useInventoryInoutDetail);
                    }

                    baseMapper.insert(useInventoryInoutDetail);
//                    }
                } else if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",creator));


//                    Integer quantity=useInventoryInoutDetailForm.getQuantity();
                    List<ProductDetail> productDetails = productDetailService.listBySkuCode(useInventoryInoutDetailForm.getSkuCode());
                    if (useInventoryInoutDetailForm.getQuantity() < 0) {
                        throw new BusinessException("领取数量参数异常");
                    }
                    Integer unitRate=1;
                    BigDecimal price=null;
                    if (productDetails.size()>0){
                        //price=productDetails.get(0).getMarketPrice();
                        price=productDetails.get(0).getBasePrice();
                    }
//                    if (productDetails.size()>0&&productDetails.get(0).getUnitRate()!=null&&productDetails.get(0).getUnitRate()>0){
//                        unitRate=productDetails.get(0).getUnitRate();
//                    }
                    if (useInventoryInoutDetailForm.getQuantityPackUnit()!=null&&useInventoryInoutDetailForm.getQuantityPackUnit()!=0){
                        unitRate=useInventoryInoutDetailForm.getQuantityPackUnit();
                    }
                    useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity()*unitRate);
                    if (skuInventoryList.size() == 0) {
                        Integer currentQuantity = 0;
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity()*unitRate;

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        useInventoryProduct.setDeviceCode(deviceCode);
                        useInventoryProduct.setEnterpriseCode(enterpriseCode);
                        useInventoryProduct.setCreator(creator);
                        useInventoryProduct.setCreatorName(creatorName);
                        useInventoryProduct.setEnterpriseCode(enterpriseCode);
                        useInventoryProduct.setChannelCode(channelCode);
                        /**
                         * 默认包装单位 一粒/片
                         */
                        useInventoryProduct.setPackId(useInventoryInoutDetailForm.getPackId());
                        useInventoryProduct.setPackName(useInventoryInoutDetailForm.getPackName());
                        useInventoryProduct.setUnitName(useInventoryInoutDetailForm.getUnitName());
                        useInventoryProduct.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                        useInventoryProduct.setQuantityPack(newQuantity);
                        inventoryProductService.save(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityProductCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityProductAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);
                    } else {

                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity()*unitRate;

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        inventoryProductService.updateById(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityProductCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityProductAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);
                    }
//                    quantity=useInventoryInoutDetailForm.getQuantity();
//                    if (skuInventoryUserList.size()==0){
//                        Integer currentQuantity=0;
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();
                    BigDecimal total=null;
                    if (price!=null){
                        total=price.multiply(BigDecimal.valueOf(useInventoryInoutDetailForm.getQuantity()*unitRate));
                    }
                    UseInventoryUser useInventoryUser = new UseInventoryUser();
                    useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    useInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity()*unitRate);
                    useInventoryUser.setCreator(creator);
                    useInventoryUser.setCreatorName(creatorName);
                    useInventoryUser.setDeviceCode(deviceCode);
                    useInventoryUser.setOrderCode(orderCode);
                    useInventoryUser.setCellInventoryInoutId(cellInventoryInoutId);
                    useInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    useInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    useInventoryUser.setUseInventoryInoutId(inventoryInoutId);
                    useInventoryUser.setUseInventoryInoutDetailId(useInventoryInoutDetail.getId());
                    useInventoryUser.setWorkOrderId(list.get(0).getWorkOrderId());
                    useInventoryUser.setProcessId(list.get(0).getProcessId());
                    useInventoryUser.setDepartmentId(departmentId);
                    useInventoryUser.setDepartmentName(departmentName);
                    useInventoryUser.setEnterpriseCode(enterpriseCode);
                    useInventoryUser.setBusinessType(UseInventoryUser.BusinessType.jsonCreator(businessDetailType.name()));
                    useInventoryUser.setRemark(useInventoryUser.getBusinessTypeDesc());
                    useInventoryUser.setChannelCode(channelCode);
                    useInventoryUser.setRoleId(roleId);
                    useInventoryUser.setRoleName(roleName);
                    useInventoryUser.setPrice(price);
                    useInventoryUser.setTotal(total);
                    /**
                     * 默认包装单位 一粒/片
                     */
                    useInventoryUser.setPackId(useInventoryInoutDetailForm.getPackId());
                    useInventoryUser.setPackName(useInventoryInoutDetailForm.getPackName());
                    useInventoryUser.setUnitName(useInventoryInoutDetailForm.getUnitName());
                    useInventoryUser.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                    useInventoryUser.setQuantityPack(useInventoryInoutDetailForm.getQuantity());

                    inventoryUserService.save(useInventoryUser);
                    useInventoryInoutDetail.setQuantityCurrent(0);
                    useInventoryInoutDetail.setQuantityAfter(useInventoryUser.getQuantity());
                    useInventoryInoutDetail.setUseInventoryUserId(useInventoryUser.getId());

                    for (int i = 0; i < useInventoryInoutDetailForm.getQuantity(); i++) {
                        UseInventoryUserKnifeSeq useInventoryUserKnifeSeq4Label = new UseInventoryUserKnifeSeq();
                        useInventoryUserKnifeSeqService.insert(useInventoryUserKnifeSeq4Label);
                        Long labelId4Label = useInventoryUserKnifeSeqService.getId();
                        String parentLabelCode = StringUtils.leftPad(labelId4Label.toString(), 10, "0");
                        for (int j=0;j<unitRate;j++){
                            /**
                            if (j==0&&unitRate>1){
                                UseInventoryUserKnifeSeq useInventoryUserKnifeSeq4Label = new UseInventoryUserKnifeSeq();
                                useInventoryUserKnifeSeqService.insert(useInventoryUserKnifeSeq4Label);
                                Long labelId4Label = useInventoryUserKnifeSeqService.getId();
                                parentLabelCode = StringUtils.leftPad(labelId4Label.toString(), 10, "0");
                            }
                            UseInventoryUserKnifeSeq useInventoryUserKnifeSeq = new UseInventoryUserKnifeSeq();
                            useInventoryUserKnifeSeqService.insert(useInventoryUserKnifeSeq);
                            Long labelId = useInventoryUserKnifeSeqService.getId();
                            String labelCode = StringUtils.leftPad(labelId.toString(), 10, "0");
                             */
                            String labelCode="";
                            if (unitRate>1){
                                labelCode=parentLabelCode+"-"+(j+1);
                            }else{
                                labelCode=parentLabelCode;
                            }
                            UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                            useInventoryUserKnife.setCode(labelCode);
                            useInventoryUserKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            useInventoryUserKnife.setUseInventoryUserId(useInventoryUser.getId());
                            useInventoryUserKnife.setUseInventoryInoutId(inventoryInoutId);
                            useInventoryUserKnife.setCellInventoryInoutId(cellInventoryInoutId);
                            useInventoryUserKnife.setDeviceCode(deviceCode);
                            useInventoryUserKnife.setCreator(creator);
                            useInventoryUserKnife.setCreatorName(creatorName);
                            useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                            useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                            useInventoryUserKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                            useInventoryUserKnife.setProcessId(list.get(0).getProcessId());
                            useInventoryUserKnife.setEnterpriseCode(enterpriseCode);
                            useInventoryUserKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            useInventoryUserKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                            useInventoryUserKnife.setOutTime(LocalDateTime.now());
                            useInventoryUserKnife.setChannelCode(channelCode);
                            useInventoryUserKnife.setDepartmentId(departmentId);
                            useInventoryUserKnife.setDepartmentName(departmentName);
                            useInventoryUserKnife.setRoleId(roleId);
                            useInventoryUserKnife.setRoleName(roleName);
                            useInventoryUserKnife.setParentCode(parentLabelCode);
                            useInventoryUserKnife.setPrice(price);


                            UseInventoryKnife useInventoryKnife = new UseInventoryKnife();
                            UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();

                            if (productDetails.size() > 0) {
                                if (productDetails.get(0).getLifeSpan() != null) {
                                    useInventoryUserKnife.setInitTime(productDetails.get(0).getLifeSpan());
                                    useInventoryUserKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                    useInventoryKnife.setRemainingTime(productDetails.get(0).getLifeSpan());
                                    useInventoryKnife.setSettingTime(productDetails.get(0).getLifeSpan());

                                    useInventoryUserKnifeInout.setInitTime(productDetails.get(0).getLifeSpan());
                                    useInventoryUserKnifeInout.setRemainingTime(productDetails.get(0).getLifeSpan());
                                }

                                if (productDetails.get(0).getLifeUnit() != null) {
                                    useInventoryKnife.setLifeUnit(UseInventoryKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                    useInventoryUserKnife.setLifeUnit(UseInventoryUserKnife.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                    useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(productDetails.get(0).getLifeUnit().name()));
                                }

                            }
                            useInventoryUserKnifeService.save(useInventoryUserKnife);


                            useInventoryKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            useInventoryKnife.setQuantity(1);
                            useInventoryKnife.setCreator(creator);
                            useInventoryKnife.setCreatorName(creatorName);
                            useInventoryKnife.setDeviceCode(deviceCode);
                            useInventoryKnife.setOrderCode(orderCode);
                            useInventoryKnife.setCellInventoryInoutId(cellInventoryInoutId);
                            useInventoryKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            useInventoryKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                            useInventoryKnife.setUseInventoryInoutId(inventoryInoutId);
                            useInventoryKnife.setUseInventoryInoutDetailId(useInventoryInoutDetail.getId());
                            useInventoryKnife.setLabelCode(labelCode);
                            useInventoryKnife.setUseInventoryUserId(useInventoryUser.getId());
                            useInventoryKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                            useInventoryKnife.setProcessId(list.get(0).getProcessId());
                            useInventoryKnife.setEnterpriseCode(enterpriseCode);
                            useInventoryKnife.setOutTime(LocalDateTime.now());
                            useInventoryKnife.setBusinessType(UseInventoryKnife.BusinessType.jsonCreator(businessDetailType.name()));
                            useInventoryKnife.setRemark(useInventoryKnife.getBusinessTypeDesc());
                            useInventoryKnife.setChannelCode(channelCode);
                            useInventoryKnife.setDepartmentId(departmentId);
                            useInventoryKnife.setDepartmentName(departmentName);
                            useInventoryKnife.setRoleId(roleId);
                            useInventoryKnife.setRoleName(roleName);
                            useInventoryKnife.setParentLabelCode(parentLabelCode);
                            useInventoryKnife.setPrice(price);
                            useInventoryKnife.setPackId(useInventoryInoutDetailForm.getPackId());
                            useInventoryKnife.setPackName(useInventoryInoutDetailForm.getPackName());

                            useInventoryKnifeService.save(useInventoryKnife);

//                            labelCodes.add(labelCode);

                            BeanUtils.copyProperties(useInventoryUserKnife, useInventoryUserKnifeInout);
                            useInventoryUserKnifeInout.setId(null);
                            useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
                            useInventoryUserKnifeInout.setCreator(creator);
                            useInventoryUserKnifeInout.setCreatorName(creatorName);
                            useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                            useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessTypeDesc());
                            useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                            useInventoryUserKnifeInout.setProcessId(list.get(0).getProcessId());
                            useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                            useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                            useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                            useInventoryUserKnifeInout.setChannelCode(channelCode);
                            useInventoryUserKnifeInout.setDepartmentId(departmentId);
                            useInventoryUserKnifeInout.setDepartmentName(departmentName);
                            useInventoryUserKnifeInout.setRoleId(roleId);
                            useInventoryUserKnifeInout.setRoleName(roleName);
                            useInventoryUserKnifeInout.setPrice(price);

                            useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);

                            // 生成领新条码明细
                            CellInventoryOutLabel cellInventoryOutLabel = new CellInventoryOutLabel();
                            log.info("生成领新条码明细设置的InoutId："+cellInventoryInoutId);
                            cellInventoryOutLabel.setInoutId(cellInventoryInoutId);
                            cellInventoryOutLabel.setInoutDetailId(useInventoryInoutDetailForm.getStorageInventoryInoutDetailId());
                            cellInventoryOutLabel.setLabelCode(labelCode);
                            cellInventoryOutLabel.setParentCode(parentLabelCode);
                            cellInventoryOutLabelService.save(cellInventoryOutLabel);
                        }
                        labelCodes.add(parentLabelCode);


                    }
                    /**
                     * 默认包装单位 一粒/片
                     */
                    useInventoryInoutDetail.setPackId(useInventoryInoutDetailForm.getPackId());
                    useInventoryInoutDetail.setPackName(useInventoryInoutDetailForm.getPackName());
                    useInventoryInoutDetail.setUnitName(useInventoryInoutDetailForm.getUnitName());
                    useInventoryInoutDetail.setQuantityPackUnit(useInventoryInoutDetailForm.getQuantityPackUnit());
                    useInventoryInoutDetail.setQuantityPack(useInventoryInoutDetailForm.getQuantity());
                    useInventoryInoutDetail.setMainCabCode(useInventoryInoutDetailForm.getMainCabCode());
                    baseMapper.insert(useInventoryInoutDetail);

//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);

//                    }else{
//                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();
//
//                        UseInventoryUser useInventoryUser=new UseInventoryUser();
//                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
//                        useInventoryUser.setQuantity(newQuantity);
//                        inventoryUserService.updateById(useInventoryUser);
//
//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);
//
//                    }
                } else {
                    throw new BusinessException("出入库参数类型异常");
                }

            }
        } else {
            throw new BusinessException("未提交领用/存放刀具数据");
        }
        return labelCodes;
    }

    //private void setDefaultVal(UseInventoryUser useInventoryUser){
    //    useInventoryUser.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    useInventoryUser.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    useInventoryUser.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    useInventoryUser.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    useInventoryUser.setQuantityPack(useInventoryUser.getQuantity());
    //}

    //private void setDefaultVal(UseInventoryProduct useInventoryProduct){
    //    useInventoryProduct.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    useInventoryProduct.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    useInventoryProduct.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    useInventoryProduct.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    useInventoryProduct.setQuantityPack(useInventoryProduct.getQuantity());
    //}

    //private void setDefaultVal(UseInventoryInoutDetail useInventoryInoutDetail){
    //    useInventoryInoutDetail.setPackId(CabConstants.DEFAULT_PACK_ID2);
    //    useInventoryInoutDetail.setPackName(CabConstants.DEFAULT_PACK_NAME2);
    //    useInventoryInoutDetail.setUnitName(CabConstants.DEFAULT_UNIT_NAME2);
    //    useInventoryInoutDetail.setQuantityPackUnit(CabConstants.QUANTITY_PACK_UNIT);
    //    useInventoryInoutDetail.setQuantityPack(useInventoryInoutDetail.getQuantity());
    //}


    List<String> saveKnife(UseInventoryUserExcelIn useInventoryInoutDetailForm, Long useInventoryUserId, Long inventoryInoutId, Long creator, String creatorName) {
//        Long creator=JwtUtils.getLoginUserId();
//        String creatorName=JwtUtils.getLoginUsername();
        List<String> labelCodes = new ArrayList<>();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        String deviceCode = useInventoryInoutDetailForm.getDeviceCode();
        String departmentName=JwtUtils.getDepartmentName();
        Long departmentId=JwtUtils.getDepartmentId();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        String channelCode=JwtUtils.getChannelCode();
        ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(useInventoryInoutDetailForm.getSkuCode());
        for (int i = 0; i < useInventoryInoutDetailForm.getQuantity(); i++) {
            UseInventoryUserKnifeSeq useInventoryUserKnifeSeq = new UseInventoryUserKnifeSeq();
            useInventoryUserKnifeSeqService.insert(useInventoryUserKnifeSeq);
            Long labelId = useInventoryUserKnifeSeqService.getId();
            String labelCode = StringUtils.leftPad(labelId.toString(), 10, "0");
            UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
            useInventoryUserKnife.setCode(labelCode);
            useInventoryUserKnife.setParentCode(labelCode);
            if (null != productDetailVO) {
                useInventoryUserKnife.setPrice(productDetailVO.getBasePrice());
            }
            useInventoryUserKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
            useInventoryUserKnife.setUseInventoryUserId(useInventoryUserId);
            useInventoryUserKnife.setUseInventoryInoutId(inventoryInoutId);
//            useInventoryUserKnife.setCellInventoryInoutId(cellInventoryInoutId);
            useInventoryUserKnife.setDeviceCode(deviceCode);
            useInventoryUserKnife.setCreator(creator);
            useInventoryUserKnife.setCreatorName(creatorName);
            useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.importUseByExcel);
            useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
//            useInventoryUserKnife.setWorkOrderId(list.get(0).getWorkOrderId());
            useInventoryUserKnife.setEnterpriseCode(enterpriseCode);
//            useInventoryUserKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
//            useInventoryUserKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
            useInventoryUserKnife.setOutTime(LocalDateTime.now());
            if (null != productDetailVO) {
                if (productDetailVO.getLifeSpan() != null) {
                    useInventoryUserKnife.setInitTime(productDetailVO.getLifeSpan());
                    useInventoryUserKnife.setRemainingTime(productDetailVO.getLifeSpan());
                }

                if (productDetailVO.getLifeUnit() != null) {
                    useInventoryUserKnife.setLifeUnit(UseInventoryUserKnife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                }

            }
            useInventoryUserKnife.setDepartmentName(departmentName);
            useInventoryUserKnife.setDepartmentId(departmentId);
            useInventoryUserKnife.setRoleName(roleName);
            useInventoryUserKnife.setRoleId(roleId);
            useInventoryUserKnife.setChannelCode(channelCode);
            useInventoryUserKnifeService.save(useInventoryUserKnife);

            UseInventoryKnife useInventoryKnife = new UseInventoryKnife();
            useInventoryKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
            useInventoryKnife.setQuantity(1);
            useInventoryKnife.setCreator(creator);
            useInventoryKnife.setCreatorName(creatorName);
            useInventoryKnife.setDeviceCode(deviceCode);
//            useInventoryKnife.setOrderCode(orderCode);
//            useInventoryKnife.setCellInventoryInoutId(cellInventoryInoutId);
//            useInventoryKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
//            useInventoryKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
            useInventoryKnife.setUseInventoryInoutId(inventoryInoutId);
//            useInventoryKnife.setUseInventoryInoutDetailId(useInventoryInoutDetail.getId());
            useInventoryKnife.setLabelCode(labelCode);
            useInventoryKnife.setUseInventoryUserId(useInventoryUserId);
//            useInventoryKnife.setWorkOrderId(list.get(0).getWorkOrderId());
            useInventoryKnife.setEnterpriseCode(enterpriseCode);
            useInventoryKnife.setOutTime(LocalDateTime.now());
            useInventoryKnife.setBusinessType(UseInventoryKnife.BusinessType.importUseByExcel);
            useInventoryKnife.setParentLabelCode(labelCode);
            if (null != productDetailVO) {
                useInventoryKnife.setPrice(productDetailVO.getBasePrice());
                useInventoryKnife.setPackId(productDetailVO.getPackId());
                useInventoryKnife.setPackName(productDetailVO.getPackName());
                if (productDetailVO.getLifeSpan() != null) {
                    useInventoryKnife.setRemainingTime(productDetailVO.getLifeSpan());
                }
                if (productDetailVO.getLifeUnit() != null) {
                    useInventoryKnife.setLifeUnit(UseInventoryKnife.LifeUnit.jsonCreator(productDetailVO.getLifeUnit().name()));
                }

            }
            useInventoryKnife.setDepartmentName(departmentName);
            useInventoryKnife.setDepartmentId(departmentId);
            useInventoryKnife.setRoleName(roleName);
            useInventoryKnife.setRoleId(roleId);
            useInventoryKnife.setChannelCode(channelCode);
            useInventoryKnifeService.save(useInventoryKnife);

            labelCodes.add(labelCode);
            UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();
            BeanUtils.copyProperties(useInventoryUserKnife, useInventoryUserKnifeInout);
            useInventoryUserKnifeInout.setId(null);
            useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
            useInventoryUserKnifeInout.setCreator(creator);
            useInventoryUserKnifeInout.setCreatorName(creatorName);
            useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.importUseByExcel);
            useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessTypeDesc());
//            useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
            useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
//            useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
//            useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
            useInventoryUserKnifeInout.setDepartmentName(departmentName);
            useInventoryUserKnifeInout.setDepartmentId(departmentId);
            useInventoryUserKnifeInout.setRoleName(roleName);
            useInventoryUserKnifeInout.setRoleId(roleId);
            useInventoryUserKnifeInout.setChannelCode(channelCode);
            useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
        }
        return labelCodes;
    }

    @Transactional
    void saveDetail4UseInoutDetailForm(List<UseInventoryInoutDetailForm> list, Long inventoryInoutId, String inOutTypeName, String businessTypeName, String deviceCode, Long storageInventoryInoutId, StorageInventoryInout.BusinessDetailType businessDetailType) {
        Long creator = JwtUtils.getLoginUserId();
        String creatorName = JwtUtils.getLoginUsername();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        Long departmentId = JwtUtils.getDepartmentId();
        String departmentName = JwtUtils.getDepartmentName();
        String channelCode=JwtUtils.getChannelCode();
        String roleName=JwtUtils.getRoleName();
        Long roleId=JwtUtils.getRoleId();
        if (CollectionUtils.isNotEmpty(list)) {
            for (UseInventoryInoutDetailForm useInventoryInoutDetailForm : list) {
                UseInventoryInoutDetail useInventoryInoutDetail = new UseInventoryInoutDetail();
                BeanUtils.copyProperties(useInventoryInoutDetailForm, useInventoryInoutDetail);
                useInventoryInoutDetail.setEnterpriseCode(enterpriseCode);
                useInventoryInoutDetail.setId(null);
                useInventoryInoutDetail.setCreator(creator);
                useInventoryInoutDetail.setCreatorName(creatorName);
                useInventoryInoutDetail.setType(UseInventoryInoutDetail.Type.jsonCreator(inOutTypeName));
                useInventoryInoutDetail.setBusinessType(UseInventoryInoutDetail.BusinessType.jsonCreator(businessTypeName));
                useInventoryInoutDetail.setInoutId(inventoryInoutId);
                useInventoryInoutDetail.setChannelCode(channelCode);
                List<UseInventoryProduct> skuInventoryList = inventoryProductService.list(new QueryWrapper<UseInventoryProduct>().eq("sku_code", useInventoryInoutDetailForm.getSkuCode()).eq("enterprise_code", enterpriseCode));
                if (UseInventoryInout.Type.out.name().equals(inOutTypeName)) {

//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",useInventoryInoutDetailForm.getCreator()));
//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id",useInventoryInoutDetailForm.getId()));
                    List<UseInventoryKnife> skuInventoryKnifeList = useInventoryKnifeService.list(new QueryWrapper<UseInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
                    if (skuInventoryKnifeList.size() == 0) {
                        throw new BusinessException("未找到SKU[" + useInventoryInoutDetailForm.getSkuCode() + "]的刀具产品");
                    } else {
                        if (StringUtils.isBlank(deviceCode)) {
                            deviceCode = skuInventoryKnifeList.get(0).getDeviceCode();
                        }
                        List<UseInventoryUser> skuInventoryUserList = inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("id", skuInventoryKnifeList.get(0).getUseInventoryUserId()));

                        useInventoryKnifeService.remove(new QueryWrapper<UseInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                        UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                        useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.inTempCab);
                        useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnife.setRemark(useInventoryUserKnife.getBusinessTypeDesc());
                        useInventoryUserKnifeService.update(useInventoryUserKnife, new QueryWrapper<UseInventoryUserKnife>().eq("code", useInventoryInoutDetailForm.getLabelCode()));


                        UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();
                        useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
                        useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryUserKnifeInout.setUseInventoryUserId(skuInventoryKnifeList.get(0).getUseInventoryUserId());
                        useInventoryUserKnifeInout.setUseInventoryInoutId(inventoryInoutId);
                        useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
//                        useInventoryUserKnifeInout.setCellInventoryInoutId(cellInventoryInoutId);
                        useInventoryUserKnifeInout.setDeviceCode(deviceCode);
                        useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.inTempCab);
                        useInventoryUserKnifeInout.setCreator(creator);
                        useInventoryUserKnifeInout.setCreatorName(creatorName);
                        useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                        useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessType() != null ? useInventoryUserKnifeInout.getBusinessType().getDesc() : "");
                        useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                        useInventoryUserKnifeInout.setProcessId(list.get(0).getProcessId());
                        useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                        useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                        useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                        useInventoryUserKnifeInout.setChannelCode(channelCode);
                        useInventoryUserKnifeInout.setDepartmentId(departmentId);
                        useInventoryUserKnifeInout.setDepartmentName(departmentName);
                        useInventoryUserKnifeInout.setRoleId(roleId);
                        useInventoryUserKnifeInout.setRoleName(roleName);
                        useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);

                        Integer quantity = useInventoryInoutDetailForm.getQuantity();
                        if (quantity > 0) {
                            quantity = -1 * quantity;
                        }
                        if (skuInventoryUserList.size() > 0) {
                            if (StringUtils.isBlank(deviceCode)) {
                                deviceCode = skuInventoryUserList.get(0).getDeviceCode();
                            }
                            Integer currentQuantity = skuInventoryUserList.get(0).getQuantity();
                            Integer newQuantity = currentQuantity + quantity;
                            if (newQuantity < 0) {
//                                throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                            }

                            UseInventoryUser useInventoryProduct = new UseInventoryUser();
                            useInventoryProduct.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                            useInventoryProduct.setQuantity(newQuantity);
                            if (newQuantity <= 0) {
                                inventoryUserService.removeById(skuInventoryUserList.get(0).getId());
                            } else {
                                inventoryUserService.updateById(useInventoryProduct);
                            }
                            if (skuInventoryList.size() > 0) {
                                useInventoryInoutDetail.setQuantityCurrent(skuInventoryList.get(0).getQuantity());
                                useInventoryInoutDetail.setQuantityAfter(skuInventoryList.get(0).getQuantity() + quantity);
                            } else {
                                useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
                                useInventoryInoutDetail.setQuantityAfter(newQuantity);
                            }
                        }


                        useInventoryInoutDetail.setQuantity(quantity);
                        useInventoryInoutDetail.setCreator(useInventoryInoutDetailForm.getCreator());
                        useInventoryInoutDetail.setCreatorName(useInventoryInoutDetailForm.getCreatorName());
                        useInventoryInoutDetail.setModifier(creator);
                        useInventoryInoutDetail.setModifierName(creatorName);
//                        baseMapper.insert(useInventoryInoutDetail);
                    }

                    if (skuInventoryList.size() > 0) {
//                        throw new BusinessException("未找到SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品");
//                    }else{
                        Integer quantity = useInventoryInoutDetailForm.getQuantity();
                        if (quantity > 0) {
                            quantity = -1 * quantity;
                        }

                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + quantity;
                        if (newQuantity < 0) {
//                            throw new BusinessException("SKU["+useInventoryInoutDetailForm.getSkuCode()+"]的刀具产品在用库存不足");
                        }

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        if (newQuantity <= 0) {
                            inventoryProductService.removeById(skuInventoryList.get(0).getId());
                        } else {
                            inventoryProductService.updateById(useInventoryProduct);
                        }
                        useInventoryInoutDetail.setQuantityProductCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityProductAfter(useInventoryProduct.getQuantity());

//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(useInventoryInoutDetail);
                    }
                    baseMapper.insert(useInventoryInoutDetail);
                } else if (UseInventoryInout.Type.in.name().equals(inOutTypeName)) {
//                    List<UseInventoryUser> skuInventoryUserList=inventoryUserService.list(new QueryWrapper<UseInventoryUser>().eq("sku_code",useInventoryInoutDetailForm.getSkuCode()).eq("creator",creator));
//                    List<StorageInventoryKnife> skuInventoryKnifeList = storageInventoryKnifeService.list(new QueryWrapper<StorageInventoryKnife>().eq("id", useInventoryInoutDetailForm.getId()));
//                    if (skuInventoryKnifeList.size()<0){
//                        throw new BusinessException("未找到刀具");
//                    }
//                    Integer quantity=useInventoryInoutDetailForm.getQuantity();
                    if (useInventoryInoutDetailForm.getQuantity() < 0) {
                        throw new BusinessException("领取数量参数异常");
                    }
                    useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    if (skuInventoryList.size() == 0) {
                        Integer currentQuantity = 0;
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        useInventoryProduct.setCreator(creator);
                        useInventoryProduct.setCreatorName(creatorName);
                        useInventoryProduct.setEnterpriseCode(enterpriseCode);
                        useInventoryProduct.setChannelCode(channelCode);
                        inventoryProductService.save(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityProductCurrent(0);
                        useInventoryInoutDetail.setQuantityProductAfter(useInventoryProduct.getQuantity());
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);
                    } else {

                        Integer currentQuantity = skuInventoryList.get(0).getQuantity();
                        Integer newQuantity = currentQuantity + useInventoryInoutDetailForm.getQuantity();

                        UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
                        useInventoryProduct.setId(skuInventoryList.get(0).getId());
//                        useInventoryProduct.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                        useInventoryProduct.setQuantity(newQuantity);
                        inventoryProductService.updateById(useInventoryProduct);

                        useInventoryInoutDetail.setQuantityProductCurrent(currentQuantity);
                        useInventoryInoutDetail.setQuantityProductAfter(useInventoryProduct.getQuantity());
//                        useInventoryInoutDetail.setQuantity(useInventoryInoutDetailForm.getQuantity());
//                        baseMapper.insert(useInventoryInoutDetail);
                    }

//                    if (skuInventoryUserList.size()==0){
//                        Integer currentQuantity=0;
//                        Integer newQuantity=currentQuantity+useInventoryInoutDetailForm.getQuantity();

                    UseInventoryUser useInventoryUser = new UseInventoryUser();
                    useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    useInventoryUser.setQuantity(useInventoryInoutDetailForm.getQuantity());
                    useInventoryUser.setCreator(creator);
                    useInventoryUser.setCreatorName(creatorName);
                    useInventoryUser.setDeviceCode(deviceCode);
//                        useInventoryUser.setOrderCode(orderCode);
                    useInventoryUser.setStorageInventoryInoutId(storageInventoryInoutId);
                    useInventoryUser.setUseInventoryInoutId(inventoryInoutId);
                    useInventoryUser.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    useInventoryUser.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    useInventoryUser.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                    useInventoryUser.setWorkOrderId(list.get(0).getWorkOrderId());
                    useInventoryUser.setProcessId(list.get(0).getProcessId());
                    useInventoryUser.setEnterpriseCode(enterpriseCode);
                    useInventoryUser.setBusinessType(UseInventoryUser.BusinessType.jsonCreator(businessTypeName));
                    useInventoryUser.setRemark(useInventoryUser.getBusinessTypeDesc());
                    useInventoryUser.setDepartmentId(departmentId);
                    useInventoryUser.setDepartmentName(departmentName);
                    useInventoryUser.setChannelCode(channelCode);
                    useInventoryUser.setRoleName(roleName);
                    useInventoryUser.setRoleId(roleId);
                    useInventoryUser.setPrice(useInventoryInoutDetailForm.getPrice());
                    useInventoryUser.setTotal(useInventoryInoutDetailForm.getPrice());
                    useInventoryUser.setQuantityPack(1);
                    inventoryUserService.save(useInventoryUser);

                    useInventoryInoutDetail.setQuantityCurrent(0);
                    useInventoryInoutDetail.setQuantityAfter(useInventoryInoutDetailForm.getQuantity());
                    useInventoryInoutDetail.setUseInventoryUserId(useInventoryUser.getId());

                    int count = useInventoryKnifeService.count(new QueryWrapper<UseInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                    if (count > 0) {
                        useInventoryKnifeService.remove(new QueryWrapper<UseInventoryKnife>().eq("label_code", useInventoryInoutDetailForm.getLabelCode()));
                    }

                    UseInventoryKnife useInventoryKnife = new UseInventoryKnife();
                    useInventoryKnife.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    useInventoryKnife.setQuantity(1);
                    useInventoryKnife.setCreator(creator);
                    useInventoryKnife.setCreatorName(creatorName);
                    useInventoryKnife.setDeviceCode(deviceCode);
//                        useInventoryUser.setOrderCode(orderCode);
                    useInventoryUser.setStorageInventoryInoutId(storageInventoryInoutId);
                    useInventoryKnife.setUseInventoryUserId(inventoryInoutId);
                    useInventoryKnife.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    useInventoryKnife.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    useInventoryKnife.setLabelCode(useInventoryInoutDetailForm.getLabelCode());
                    useInventoryKnife.setUseInventoryUserId(useInventoryUser.getId());
                    useInventoryKnife.setWorkOrderId(list.get(0).getWorkOrderId());
                    useInventoryKnife.setEnterpriseCode(enterpriseCode);
                    useInventoryKnife.setBusinessType(UseInventoryKnife.BusinessType.jsonCreator(businessTypeName));
                    useInventoryKnife.setRemark(useInventoryKnife.getBusinessTypeDesc());
                    useInventoryKnife.setRemainingTime(useInventoryInoutDetailForm.getRemainingTime());
                    useInventoryKnife.setSettingTime(useInventoryInoutDetailForm.getSettingTime());
                    useInventoryKnife.setParentLabelCode(useInventoryInoutDetailForm.getParentLabelCode());

                    UseInventoryUserKnifeInout useInventoryUserKnifeInout = new UseInventoryUserKnifeInout();
                    useInventoryUserKnifeInout.setRemainingTime(useInventoryInoutDetailForm.getRemainingTime());
                    useInventoryUserKnifeInout.setPreTime(useInventoryInoutDetailForm.getRemainingTime());
                    useInventoryUserKnifeInout.setUseTime(0);
                    if (useInventoryInoutDetailForm.getLifeUnit() != null) {
                        useInventoryKnife.setLifeUnit(UseInventoryKnife.LifeUnit.jsonCreator(useInventoryInoutDetailForm.getLifeUnit().name()));
                        useInventoryUserKnifeInout.setLifeUnit(UseInventoryUserKnifeInout.LifeUnit.jsonCreator(useInventoryInoutDetailForm.getLifeUnit().name()));
                    }
                    useInventoryKnife.setDepartmentId(departmentId);
                    useInventoryKnife.setDepartmentName(departmentName);
                    useInventoryKnife.setRoleId(roleId);
                    useInventoryKnife.setRoleName(roleName);
                    useInventoryKnife.setChannelCode(channelCode);
                    useInventoryKnife.setPrice(useInventoryInoutDetailForm.getPrice());
                    useInventoryKnife.setPackId(useInventoryInoutDetailForm.getPackId());
                    useInventoryKnife.setPackName(useInventoryInoutDetailForm.getPackName());
                    useInventoryKnifeService.save(useInventoryKnife);


                    UseInventoryUserKnife useInventoryUserKnife = new UseInventoryUserKnife();
                    useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.used);
                    useInventoryUserKnife.setBusinessType(UseInventoryUserKnife.BusinessType.jsonCreator(businessDetailType.name()));
                    useInventoryUserKnife.setStorageInventoryUserId(useInventoryUser.getId());
                    useInventoryUserKnife.setStorageInventoryInoutId(storageInventoryInoutId);
                    useInventoryUserKnifeService.update(useInventoryUserKnife, new QueryWrapper<UseInventoryUserKnife>().eq("code", useInventoryInoutDetailForm.getLabelCode()));


                    useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
                    useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
                    useInventoryUserKnifeInout.setUseInventoryInoutId(inventoryInoutId);
                    useInventoryUserKnifeInout.setUseInventoryUserId(useInventoryUser.getId());
                    useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
                    useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                    useInventoryUserKnifeInout.setCreator(creator);
                    useInventoryUserKnifeInout.setCreatorName(creatorName);
//                        useInventoryUserKnifeInout.setUseInventoryInoutId()
                    useInventoryUserKnifeInout.setBusinessType(UseInventoryUserKnifeInout.BusinessType.jsonCreator(businessDetailType.name()));
                    useInventoryUserKnifeInout.setRemark(useInventoryUserKnifeInout.getBusinessType() != null ? useInventoryUserKnifeInout.getBusinessType().getDesc() : "");
                    useInventoryUserKnifeInout.setWorkOrderId(list.get(0).getWorkOrderId());
                    useInventoryUserKnifeInout.setProcessId(list.get(0).getProcessId());
                    useInventoryUserKnifeInout.setEnterpriseCode(enterpriseCode);
                    useInventoryUserKnifeInout.setCabCode(useInventoryInoutDetailForm.getCabCode());
                    useInventoryUserKnifeInout.setSpaceCode(useInventoryInoutDetailForm.getSpaceCode());
                    useInventoryUserKnifeInout.setDeviceCode(deviceCode);
                    useInventoryUserKnifeInout.setDepartmentName(departmentName);
                    useInventoryUserKnifeInout.setDepartmentId(departmentId);
                    useInventoryUserKnifeInout.setRoleName(roleName);
                    useInventoryUserKnifeInout.setRoleId(roleId);
                    useInventoryUserKnifeInout.setChannelCode(channelCode);
                    useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);

                    /**
                     if (StringUtils.isNotBlank(useInventoryInoutDetailForm.getLabelCode())){
                     UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
                     useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.used);
                     useInventoryUserKnife.setStorageInventoryUserId(useInventoryUser.getId());
                     useInventoryUserKnife.setStorageInventoryInoutId(storageInventoryInoutId);
                     useInventoryUserKnifeService.update(useInventoryUserKnife,new QueryWrapper<UseInventoryUserKnife>().eq("code",useInventoryInoutDetailForm.getLabelCode()));
                     UseInventoryUserKnifeInout useInventoryUserKnifeInout=new UseInventoryUserKnifeInout();
                     useInventoryUserKnifeInout.setStatus(UseInventoryUserKnifeInout.Status.used);
                     useInventoryUserKnifeInout.setCode(useInventoryInoutDetailForm.getLabelCode());
                     useInventoryUserKnifeInout.setUseInventoryInoutId(inventoryInoutId);
                     useInventoryUserKnifeInout.setUseInventoryUserId(useInventoryUser.getId());
                     useInventoryUserKnifeInout.setStorageInventoryInoutId(storageInventoryInoutId);
                     useInventoryUserKnifeInout.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
                     //                        useInventoryUserKnifeInout.setUseInventoryInoutId()
                     useInventoryUserKnifeInoutService.save(useInventoryUserKnifeInout);
                     }else{
                     List<UseInventoryUserKnife> useInventoryUserKnives=useInventoryUserKnifeService.list(new QueryWrapper<UseInventoryUserKnife>().eq("use_inventory_user_id",useInventoryInoutDetailForm.getId()).eq("status",UseInventoryUserKnife.Status.inTempCab.getValue()));
                     int size=useInventoryUserKnives.size();
                     if (size>useInventoryInoutDetailForm.getQuantity()){
                     size=useInventoryInoutDetailForm.getQuantity();
                     }
                     for (int i=0;i<size;i++){
                     UseInventoryUserKnife useInventoryUserKnife=new UseInventoryUserKnife();
                     useInventoryUserKnife.setStatus(UseInventoryUserKnife.Status.used);
                     useInventoryUserKnife.setId(useInventoryUserKnives.get(i).getId());
                     useInventoryUserKnifeService.updateById(useInventoryUserKnife);
                     }
                     }*/

//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(useInventoryInoutDetail);

//                    }else{
//                        Integer currentQuantity=skuInventoryUserList.get(0).getQuantity();
//                        Integer newQuantity=currentQuantity+quantity;
//
//                        UseInventoryUser useInventoryUser=new UseInventoryUser();
//                        useInventoryUser.setId(skuInventoryUserList.get(0).getId());
//                        useInventoryUser.setSkuCode(useInventoryInoutDetailForm.getSkuCode());
//                        useInventoryUser.setQuantity(newQuantity);
//                        inventoryUserService.updateById(useInventoryUser);
//
//                        useInventoryInoutDetail.setQuantityCurrent(currentQuantity);
//                        useInventoryInoutDetail.setQuantityAfter(newQuantity);
//                        useInventoryInoutDetail.setQuantity(quantity);
//                        baseMapper.insert(useInventoryInoutDetail);
//
//                    }
                    baseMapper.insert(useInventoryInoutDetail);
                } else {
                    throw new BusinessException("出入库参数类型异常");
                }

            }
        } else {
            throw new BusinessException("未提交领用/存放刀具数据");
        }
    }

    @Transactional(readOnly = false)
    public void importExcel(List<UseInventoryUserExcelIn> list) {
        try {
            addExcel(list);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    void addExcel(List<UseInventoryUserExcelIn> list) {
//        LocalDateTime createTime = null;
        Map<String, UserVO> map = new HashMap<>();
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        String channelCode=JwtUtils.getChannelCode();
        for (UseInventoryUserExcelIn item : list) {
            UseInventoryUser useInventoryUser = new UseInventoryUser();
//            if(isValidDate(item.getCreateTime())){
//                StringBuilder sb = new StringBuilder(item.getCreateTime());
//                String insert = sb.insert(10, " ").toString();
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                createTime = LocalDateTime.parse(insert, formatter);
//            }else {
//                String time = item.getCreateTime()+" 00:00:00";
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//                createTime = LocalDate.parse(time, formatter).atStartOfDay();
//            }
            useInventoryUser.setDeviceCode(item.getDeviceCode());
            useInventoryUser.setSkuCode(item.getSkuCode());
            useInventoryUser.setQuantity(item.getQuantity());
            useInventoryUser.setCreatorName(item.getCreatorName());
          //  useInventoryUser.setCreateTime(createTime);
            //skuCode 人
            Long creator = null;
            String creatorName = null;
            Long departmentId = null;
            String departmentName = null;
            String roleName=null;
            Long roleId=null;
            QueryWrapper<UseInventoryUser> queryWrapper = new QueryWrapper<>();
            //判断是否查询过
            UserVO userVO = map.get(useInventoryUser.getCreatorName());

            if (userVO == null) {
                JsonResult<UserVO> jsonResult = userClient.findUserByName(useInventoryUser.getCreatorName());
                if (jsonResult.getCode() == 200 && jsonResult.getData() != null) {
//                    useInventoryUser.setCreatorName(jsonResult.getData().getUsername());
                    creator = jsonResult.getData().getId();
                    creatorName = jsonResult.getData().getNickname() + "|" + jsonResult.getData().getUsername();
                    departmentName = jsonResult.getData().getDepartmentName();
                    departmentId = jsonResult.getData().getDepartmentId();
                    roleId=jsonResult.getData().getRoleId();
                    roleName=jsonResult.getData().getRoleName();
                    map.put(item.getCreatorName(), jsonResult.getData());
                    //查询完了放到map中
                    map.put(useInventoryUser.getCreatorName(), jsonResult.getData());
                } else {
                    creatorName = item.getCreatorName();
                    throw new BusinessException("用户不存在");
                }
            } else {
                creator = userVO.getId();
                creatorName = userVO.getNickname() + "|" + userVO.getUsername();
                departmentId = userVO.getDepartmentId();
                departmentName = userVO.getDepartmentName();
            }
            /*queryWrapper.like("creator_name",useInventoryUser.getCreatorName());
            queryWrapper.eq("sku_code",useInventoryUser.getSkuCode());
            queryWrapper.eq("enterprise_code",enterpriseCode);
            UseInventoryUser one = inventoryUserService.getOne(queryWrapper);*/
            useInventoryUser.setDepartmentId(departmentId);
            useInventoryUser.setDepartmentName(departmentName);
            useInventoryUser.setCreator(creator);
            useInventoryUser.setCreatorName(creatorName);
            useInventoryUser.setEnterpriseCode(enterpriseCode);
            useInventoryUser.setChannelCode(channelCode);
            useInventoryUser.setRoleId(roleId);
            useInventoryUser.setRoleName(roleName);
            /*if(one !=null){
                inventoryUserService.updateById(useInventoryUser);
            }else {
                useInventoryUser.setEnterpriseCode(enterpriseCode);

            }*/
            inventoryUserService.save(useInventoryUser);
           // UseInventoryProduct useInventoryProduct = JSON.parseObject(JSON.toJSONString(item), UseInventoryProduct.class);
            UseInventoryProduct useInventoryProduct = new UseInventoryProduct();
          //  useInventoryProduct.setCreateTime(createTime);
            useInventoryProduct.setDeviceCode(item.getDeviceCode());
            useInventoryProduct.setSkuCode(item.getSkuCode());
            useInventoryProduct.setQuantity(item.getQuantity());
            useInventoryProduct.setCreatorName(item.getCreatorName());
            // skuCode
            QueryWrapper<UseInventoryProduct> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("sku_code", useInventoryUser.getSkuCode());
            queryWrapper1.eq("enterprise_code", enterpriseCode);
            UseInventoryProduct proOne = inventoryProductService.getOne(queryWrapper1);
            if (proOne != null) {
                useInventoryProduct.setId(proOne.getId());
                useInventoryProduct.setQuantity(proOne.getQuantity() + useInventoryUser.getQuantity());
                inventoryProductService.updateById(useInventoryProduct);
            } else {
//                useInventoryProduct.setCreator(creator);
//                useInventoryProduct.setCreatorName(creatorName);
                useInventoryProduct.setEnterpriseCode(enterpriseCode);
                inventoryProductService.save(useInventoryProduct);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            UseInventoryInout useInventoryInout = new UseInventoryInout();
            String code = dynamicService.getDayNextCode("cab_use_inventory_inout");
            String day = simpleDateFormat.format(new Date());
            useInventoryInout.setCode("IN-" + day + "-" + code);
            useInventoryInout.setDay(Integer.valueOf(day));
            useInventoryInout.setNo(Integer.valueOf(code));
            useInventoryInout.setCreator(JwtUtils.getLoginUserId());
            useInventoryInout.setCreatorName(JwtUtils.getLoginUsername());
            useInventoryInout.setType(UseInventoryInout.Type.importByExcel);
            useInventoryInout.setDeviceCode(item.getDeviceCode());
            useInventoryInout.setChannelCode(channelCode);
            useInventoryInout.setDepartmentName(departmentName);
            useInventoryInout.setDepartmentId(departmentId);
            useInventoryInout.setRoleName(roleName);
            useInventoryInout.setRoleId(roleId);
            useInventoryInout.setEnterpriseCode(enterpriseCode);
            inventoryInoutService.save(useInventoryInout);
            saveUseInventoryInoutDetail(useInventoryInout, item.getQuantity(), item.getSkuCode());
            List<String> labelCodeList = saveKnife(item, useInventoryUser.getId(), useInventoryInout.getId(), creator, creatorName);

            // 添加刀具生命周期  --  批量导入在用
            cutterLifeCycleService.addLifeCycle(labelCodeList, CutterLifeCycle.Status.batchInUse, null, null, useInventoryInout.getCode(), item.getDeviceCode());
        }
    }

    void saveUseInventoryInoutDetail(UseInventoryInout useInventoryInout, Integer quantity, String skuCode) {
        UseInventoryInoutDetail useInventoryInoutDetail = new UseInventoryInoutDetail();
        useInventoryInoutDetail.setInoutId(useInventoryInout.getId());
        useInventoryInoutDetail.setQuantity(quantity);
        useInventoryInoutDetail.setType(UseInventoryInoutDetail.Type.in);
        useInventoryInoutDetail.setSkuCode(skuCode);
        useInventoryInoutDetail.setBusinessType(UseInventoryInoutDetail.BusinessType.importUseByExcel);
        this.save(useInventoryInoutDetail);
    }


    public static boolean isValidDate(String dateStr){
        //判断结果 默认为true
        boolean judgeresult=true;
        //1、首先使用SimpleDateFormat初步进行判断，过滤掉注入 yyyy-01-32 或yyyy-00-0x等格式
        //此处可根据实际需求进行调整，如需判断yyyy/MM/dd格式将参数改掉即可
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHH:mm");
        try{
            //增加强判断条件，否则 诸如2022-02-29也可判断出去
            format.setLenient(false);
            format.parse(dateStr);
            System.out.println(dateStr);
        }catch(Exception e){
            judgeresult=false;
        }
        return judgeresult;
    }

}
